我使用扫描器方法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初学者来说,这是一个非常基本的问题。当我开始学习java(自学)时,我也遇到过同样的问题。 实际上,当我们获取一个整数dataType的输入时,它只读取整数值,并留下newLine(\n)字符和这一行(即。留下新的行整数动态输入)会在我们尝试新的输入时产生问题。 如。比如,如果我们取一个整数输入然后尝试取一个字符串输入。

value1=sc.nextInt();
value2=sc.nextLine();

value2将自动读取换行符,而不接受用户输入。

解决方案: 我们只需要在获取下一个用户输入之前添加一行代码。

sc.nextLine();

or

value1=sc.nextInt();
sc.nextLine();
value2=sc.nextLine();

注意:不要忘记关闭Scanner,防止内存泄漏;

其他回答

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

使用input.next()而不是input.nextLine(),这应该可以解决问题。

修改代码:

public static Scanner input = new Scanner(System.in);

public static void main(String[] args)
{
    System.out.print("Insert a number: ");
    int number = input.nextInt();
    System.out.print("Text1: ");
    String text1 = input.next();
    System.out.print("Text2: ");
    String text2 = input.next();
}

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

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)

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

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

对于java初学者来说,这是一个非常基本的问题。当我开始学习java(自学)时,我也遇到过同样的问题。 实际上,当我们获取一个整数dataType的输入时,它只读取整数值,并留下newLine(\n)字符和这一行(即。留下新的行整数动态输入)会在我们尝试新的输入时产生问题。 如。比如,如果我们取一个整数输入然后尝试取一个字符串输入。

value1=sc.nextInt();
value2=sc.nextLine();

value2将自动读取换行符,而不接受用户输入。

解决方案: 我们只需要在获取下一个用户输入之前添加一行代码。

sc.nextLine();

or

value1=sc.nextInt();
sc.nextLine();
value2=sc.nextLine();

注意:不要忘记关闭Scanner,防止内存泄漏;