开发者社区 问答 正文

使用for循环将字符串输入数组,但是会跳过第一个索引[重复]

我正在使用这些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()执行,我希望他们能。

展开
收起
被纵养的懒猫 2019-10-08 17:15:56 491 分享 版权
阿里云 AI 助理回答

你遇到的问题是由于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

通过这种方式,你的程序将按预期顺序等待所有输入。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答地址: