我正在使用这些Scanner方法nextInt()并nextLine()读取输入。
看起来像这样:
System.out.println("Enter numerical value");
int option; option = input.nextInt(); // Read numerical value from input System.out.println("Enter 1st string"); String string1 = input.nextLine(); // Read 1st string (this is skipped) System.out.println("Enter 2nd string"); String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value) 问题是输入数值后,第一个input.nextLine()被跳过,第二个input.nextLine()被执行,因此我的输出看起来像这样:
Enter numerical value 3 // This is my input Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped Enter 2nd string // ...and this line is executed and waits for my input 我测试了我的应用程序,看起来问题出在使用中input.nextInt()。如果我删除它,然后这两个string1 = input.nextLine()和string2 = input.nextLine()执行,我希望他们能。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
你遇到的问题是由于nextInt()
方法在读取整数后,并没有读取换行符(即回车键),这个换行符依然留在输入缓冲区中。因此,接下来的nextLine()
调用会直接读取到这个换行符,认为用户已经输入了一行(尽管这一行实际上是空的),从而导致第一个字符串输入被跳过。
为了解决这个问题,你可以在读取完数值之后,立即添加一个额外的nextLine()
调用来消耗掉那个遗留的换行符。这样就能确保后续的nextLine()
调用能正确等待用户输入字符串了。修改后的代码如下:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
// Add this line to consume the newline character left by nextInt()
input.nextLine();
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Now it should wait for your 1st string input
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // And this will wait for your 2nd string input as expected
通过这种方式,你的程序将按预期顺序等待所有输入。