我使用扫描器方法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()都按照我想要的方式执行。


当前回答

关于java.util.Scanner的这个问题似乎有很多问题。我认为一个更可读/惯用的解决方案是调用scanner.skip("[\r\n]+")在调用nextInt()后删除任何换行符。

编辑:正如下面提到的@PatrickParker,如果用户在数字后输入任何空白,这将导致无限循环。关于更好的skip模式,请参阅他们的回答:https://stackoverflow.com/a/42471816/143585

其他回答

问题出在input.nextInt()方法上——它只读取int值。因此,当您继续使用input.nextLine()读取时,您会收到“\n”输入键。所以要跳过这个,你必须添加input.nextLine()。希望这一点现在应该清楚了。

试着这样做:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

在我的一个用例中,我有这样的场景:读取一个字符串值之前有几个整数值。我必须使用“for / while循环”来读取值。以上的建议在这个案例中都不起作用。

使用input.next()而不是input.nextLine()修复了这个问题。希望这对那些遇到类似情况的人有所帮助。

如果你想同时读取字符串和int,一个解决方案是使用两个扫描仪:

Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);

intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);

intScanner.close();
stringScanner.close();

nextLine()将直接将enter读取为空行,而不等待文本。

简单的解决方案是添加一个额外的扫描器来消耗空行:

System.out.println("Enter numerical value");    
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
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)

与解析输入相比,sc.nextLine()更好。 因为就性能而言,它会很好。