gpt4 book ai didi

java - 扫描程序在使用next()或nextFoo()之后跳过nextLine()吗?

转载 作者:行者123 更新时间:2023-12-01 17:56:33 24 4
gpt4 key购买 nike

我正在使用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()都将按照我希望的方式执行。

最佳答案

这是因为Scanner.nextInt方法不会在您按“ Enter”键创建的输入中读取换行符,因此对Scanner.nextLine的调用在读取该换行符后返回。

Scanner.nextLine或任何Scanner.next()方法(Scanner.nextFoo本身除外)之后使用nextLine时,您将遇到类似的行为。

解决方法:


在每个Scanner.nextLineScanner.nextInt之后放置一个Scanner.nextFoo调用以消耗该行的其余部分,包括换行符

int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();

或者,甚至更好的是,通过 Scanner.nextLine读取输入并将输入转换为所需的正确格式。例如,您可以使用 Integer.parseInt(String)方法转换为整数。

int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();

关于java - 扫描程序在使用next()或nextFoo()之后跳过nextLine()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60705055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com