java - Console.getLine 和 Console.getString 不接受所有用户输入 - JAVA
问题描述
我正在尝试接受用户输入(国家名称)以添加到我显示的国家列表中。但是,它不允许我输入超过 8 个字符的国家/地区名称。例如,当我输入“Venezuela”时,输出是“Venezuel”,当我输入“United States”时,输出是“United S”。下面是我用来接受用户输入的方法。我已经尝试过 Console.getString 和 Console.getLine ,但都不能接受超过 8 个字符。
public static void addCountry() {
String name = Console.getString("Enter country name: ");
Country country = new Country();
country.setName(name);
countryDAO.add(country);
System.out.println();
System.out.println(name
+ " has been added.\n");
}
我在 Console 类中也有这些方法
import java.util.Scanner;
public class Console {
private static Scanner sc = new Scanner(System.in);
public static String getLine(String prompt) {
System.out.print(prompt);
String s = sc.nextLine();
return s;
}
public static String getString(String prompt) {
System.out.print(prompt);
String s = sc.next();
sc.nextLine();
return s;
}
}
解决方案
使用它来获取输入而不是 sc.next():
String s = sc.nextLine();
并删除您添加 sc.nextLine() 的下一行
希望有帮助!
推荐阅读
- javascript - MPEG DASH:使用 Simple DASH Player 从 .m4s 文件而不是 MPD 文件中的字节范围播放视频片段
- visual-studio-code - 在 JSX 中,加热输入后不会在具有右缩进的标签之间创建新行
- asp.net-core - 无论 IdealTimout 设置如何,ASP.NET 核心会话都会过期
- lambda - C#如何将Linq Lambda参数传递给SwitchExpression并接收表达式
> 在 Lambda 中。Where(...) - ruby-on-rails - Rails:输入后更新属性
- php - 如何通过控制器 laravel 设置语言环境
- kotlin - 如果第一个为空,switchIfEmpty 不会从第二个 observable 发出值
- java - 在另一个类中调用函数
- javascript - CSS 过渡没有 jQuery;显示然后隐藏
- haskell - Haskell - 无法构造无限类型