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


当前回答

为什么不使用一个新的扫描器每次读取?像下面。用这种方法你就不会直面你的问题。

int i = new Scanner(System.in).nextInt();

其他回答

问题出在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();

使用此代码,它将解决您的问题。

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)

这是因为当您输入一个数字然后按enter时,input.nextInt()只使用该数字,而不是“行结束”。当input. nextline()执行时,它使用仍然在第一个输入缓冲区中的“行尾”。

相反,在input.nextInt()之后立即使用input.nextLine()

因为nextXXX()方法不读取换行符,除了nextLine()。我们可以在读取任何非字符串值(在这种情况下是int)后跳过换行符,使用scanner.skip()如下所示:

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);

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

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