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


当前回答

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

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)

其他回答

使用两个扫描仪对象而不是一个

Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");    
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();

这样做是因为input.nextInt();不捕获换行符。你可以像其他人一样通过添加input.nextLine();在下面。 或者你也可以用c#风格,把nextLine解析成一个整数,如下所示:

int number = Integer.parseInt(input.nextLine()); 

这样做效果很好,而且节省了一行代码。

要解决这个问题,只需创建scan. nextline(),其中scan是Scanner对象的一个实例。例如,我使用一个简单的HackerRank问题来解释。

package com.company;
import java.util.Scanner;

public class hackerrank {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();
    scan.nextLine(); // This line shall stop the skipping the nextLine() 
    String s = scan.nextLine();
    scan.close();



    // Write your code here.

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}

}

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

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

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

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