use*_*149 2 java java.util.scanner
所以我Scanner scan早先实例化了很多,但它在我的第二个scan.nextLine()之后跳过了scan.nextInt().我不明白为什么会跳过它?
System.out.println("Something: ");
String name = scan.nextLine();
System.out.println("Something?: ");
int number = scan.nextInt();
System.out.println("Something?: ");
String insurer = scan.nextLine();
System.out.println("Something?: ");
String another = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
因为当你输入一个数字
int number = scan.nextInt();
Run Code Online (Sandbox Code Playgroud)
你输入一些数字并点击enter,它只接受数字并在缓冲区中保留新行字符
所以nextLine()只会看到终结符字符并且它会假设它是空白字符串作为输入,修复它scan.nextLine()在处理后添加一个int
例如:
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // <--
Run Code Online (Sandbox Code Playgroud)
当您调用它时,int number = scan.nextInt();它不会消耗已推送的回车符,因此这是在下一个中执行的scan.nextLine();
你希望你的代码是
....
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // add this
System.out.println("Something?: ");
String insurer = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
nextInt()不会消耗换行符\n。这意味着在缓冲区中已经存在的换行符nextInt()将被忽略。nextLine()在 之后调用时nextInt(),nextLine()将消耗
解决方案
int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();
System.out.println("Something?: ");
String insurer = scan.nextLine();
Run Code Online (Sandbox Code Playgroud)
或者
//Parse the string to interger explicitly
String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();
int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5842 次 |
| 最近记录: |