问题描述
 
     以下是两个脚本,只是要求用户输入的顺序不同。 
     脚本1起作用,而脚本2不能按预期工作。 
     在脚本1中,我首先问name问题,然后问age问题。 
     在脚本2中,我先问age问题,然后问name问题。 
脚本1(有效):
import java.util.Scanner;
public class Example2 {
    public static void main(String[] args) {
        // Initiate a new Scanner
        Scanner userInputScanner = new Scanner(System.in);
        // Name Question
        System.out.print("\nWhat is your name? ");
        String name = userInputScanner.nextLine();
        // Age Question
        System.out.print("How old are you?");
        int age = userInputScanner.nextInt();
        System.out.println("\nHello " + name + ". You are " + age
                + " years old");
    }
}
脚本2(无效):
import java.util.Scanner;
public class Example2 {
    public static void main(String[] args) {
        // Initiate a new Scanner
        Scanner userInputScanner = new Scanner(System.in);
        // Age Question
        System.out.print("How old are you?");
        int age = userInputScanner.nextInt();
        // Name Question
        System.out.print("\nWhat is your name? ");
        String name = userInputScanner.nextLine();
        System.out.println("\nHello " + name + ". You are " + age
                + " years old");
    }
}
 
     在脚本2中,用户输入age ,他/她将以下内容打印到控制台: 
What is your name? 
Hello . You are 28 years old
 
     然后脚本结束,不允许他/她输入name 
我的问题:脚本2为什么不起作用? 我该怎么做才能使脚本#2正常工作(同时保持输入顺序)
1楼
阅读年龄后,您必须消耗EOL(行尾):
    System.out.print("How old are you?");
    int age = userInputScanner.nextInt();
    userInputScanner.nextLine();
    // Name Question
    System.out.print("\nWhat is your name? ");
    String name = userInputScanner.nextLine();
 
     如果不这样做,则EOL符号将以String name = userInputScanner.nextLine(); 
     这就是为什么您不能输入它的原因。 
2楼
当您读取一行时,它将读取整行直到结尾。
 
     例如,当您读取数字时,它只会读取数字,而不会读取行尾,除非您再次调用nextInt() ,在这种情况下,它将新行读取为空白。 
简而言之,如果您希望输入忽略数字后的任何内容,请输入
int age = userInputScanner.nextInt();
userInputScanner.nextLine(); // ignore the rest of the line.
 
     在您的情况下,您的nextLine()将读取数字后的文本,如果您未输入任何内容,则为空字符串。 
3楼
 
     nextInt()方法不会消耗输入流中的回车符。 
     您需要自己食用。 
import java.util.Scanner;
public class Example2 {
    public static void main(String[] args) {
        // Initiate a new Scanner
        Scanner userInputScanner = new Scanner(System.in);
        // Age Question
        System.out.print("How old are you?");
        int age = userInputScanner.nextInt();
        // consume carriage return
        userInputScanner.nextLine();
        // Name Question
        System.out.print("\nWhat is your name? ");
        String name = userInputScanner.nextLine();
        System.out.println("\nHello " + name + ". You are " + age
                + " years old");
    }
}
4楼
如果用户输入数字(假设输入21),则输入实际上是:“ 21 \\ n”。
您需要通过附加调用nextLine来跳过“ \\ n”:
// Age Question
System.out.print("How old are you?");
int age = userInputScanner.nextInt();
userInputScanner.nextLine(); // skip "\n"