0

I'm working in a larger program where I have a while loop that asks two questions and gets two inputs. Whenever the second loop of the while loop happens, it displays both the outputs without taking an input after the first one and then takes the input for the second one.

Here is a small example to demonstrate my problem:

public class Tests{

    public static void main(String args[]){

        Scanner Scan = new Scanner(System.in);

        while (true){

            System.out.println("Please enter your name: ");
            String name = Scan.nextLine();
            System.out.println("Please enter your age: ");
            int age = Scan.nextInt();

            System.out.println(name + age);
        }   
    }
}

The first loop through works fine. Then the second time through though, it outputs

Please enter your name: 
Please enter your age:

It skips over the first input in every loop after the first one. Why?

Chris G
  • 80
  • 1
  • 2
  • 9

1 Answers1

0

You need to call

Scan.nextLine();

after the line

int age = Scan.nextInt();

This consumes the end of line character in the buffer.

An alternate approach would be to use scan.nextLine() and parse the input to an integer like this:

int age = Integer.parseInt(Scan.nextLine());
jheimbouch
  • 929
  • 8
  • 19