Different Java Scanner for input of different types

后端 未结 5 491
不思量自难忘°
不思量自难忘° 2021-01-16 06:40

Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.

int age=0;
String name;
Scanner sc = new Scanne         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-16 07:21

    You were not given a chance to enter the name because nextInt() doesn't read the new-line character '\n' (inputted by user after pressing Enter), whereas nextLine() does. So as soon as you call name = sc.nextLine();, it will just read the '\n' character that the nextInt() didn't read already.

    Definitely do not create a new Scanner if the Scanner if you're scanning the same thing (like System.in) - only change Scanners if you are scanning something else, like different files or something.

    To get your code working (with only one Scanner instance), use this:

    int age = 0;
    String name;
    Scanner sc = new Scanner(System.in);
    
    System.out.print("Enter Age: ");
    age = sc.nextInt();
    System.out.print("Enter Name: ");
    
    sc.nextLine(); // "dispose" of the '\n' character
                   // so that it is not recorded by the next line
    
    name = sc.nextLine();
    
    // print your findings
    System.out.println("------\nAge: " + age + "\nName: " + name);
    

    Example input/output:

    Enter Age: 17
    Enter Name: Michael
    ------
    Age: 17
    Name: Michael
    

提交回复
热议问题