0

I'm new to java and I made this program, the problem I'm asking the user to input their age and name then the program should use the input to print the statement. however the when I type the age then press enter the program executes all the statements without waiting for me to enter my name.. how can I fix this?

    Scanner input =     new Scanner(System.in);
    int age;
    String name;

    System.out.println("Please enter your age ");
    age = input.nextInt();
    System.out.println("and now enter your name");
    name = input.nextLine();

    System.out.println("Your name is " +name + " and you're " +age + "years old");
maya91
  • 47
  • 8
  • Possible duplicate of [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – user3437460 Feb 27 '16 at 11:18

2 Answers2

0

You can use nextLine() for both:

System.out.println("Please enter your age ");
age = Integer.parseInt(input.nextLine());
System.out.println("and now enter your name");
name = input.nextLine();

The problem is that when you hit Enter after you input the age, the resulting newline is interpreted as the end of the input for the following nextLine().

You could also use next() instead of nextLine(), but then John Doe would be interpreted as just John because next() uses whitespace as a separator.

pp_
  • 3,171
  • 3
  • 17
  • 27
0

Use next() instead of nextLine() at name variable.

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

        System.out.println("Please enter your age ");
        age = input.nextInt();
        System.out.println("and now enter your name");
        name = input.next();

        System.out.println("Your name is " +name + " and you're " +age + " years old");
    }
Zoka
  • 291
  • 2
  • 8