Trouble using nextInt and nextLine()

2019-01-12 08:34发布

问题:

It's not letting me put my name in but it does the age works fine. I know i can change the order of the statements but is there another way I could do it?

import java.util.Scanner;

public class ScannerErr2
{
  public static void main(String [] args)
  {
    Scanner keyboard= new Scanner(System.in);
    String name;
    int    age;

    System.out.print("Enter your age : ");
    age= keyboard.nextInt();
    System.out.print("Enter your name: ");
    name= keyboard.nextLine();

    System.out.println("Age : "+age);
    System.out.println("Name: "+name);
  }
}

回答1:

You problem is that the next int doesn't consider the new line character which goes in the input for your name part. Hence name is returned as blank.

You can change your code in 2 ways:

System.out.print("Enter your age : ");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.print("Enter your name: ");
name = keyboard.nextLine();

or

System.out.print("Enter your age : ");
age = Integer.parseInt(keyboard.nextLine().trim());
System.out.print("Enter your name: ");
name = keyboard.nextLine();

I personally like the second way.



标签: java int line next