0

In Java, I have tried

try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNextLine()) {
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
    }
}

but it doesn't output Name: before asking for the input.

The console just shows an empty console window in which I can input the name.

How can I make sure Name: is outputted before asking for the name?

Edit

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");

    while (sc.hasNextLine()) {
        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");

        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.println("Age is " + age);

        System.out.print("Name: ");
    }
Jamgreen
  • 8,491
  • 24
  • 79
  • 186

3 Answers3

0

Put your println before the while loop and then add one at the end.

try (Scanner sc = new Scanner(System.in)) {
    System.out.print("Name: ");        
    while (sc.hasNextLine()) {

        String name = sc.nextLine();
        System.out.println("Name is \"" + name + "\"");
        System.out.print("Name: ");
    }
}

The scanner waits until it receives input before it runs the next code so just put the print before the scanner and then at the end of the while loop.

10 Replies
  • 396
  • 8
  • 25
0

You should put System.out.print("Name: "); before of the while loop like this:

  try (Scanner sc = new Scanner(System.in)) {
        System.out.print("Name: ");
        while (sc.hasNextLine()) {
            String name = sc.nextLine();
            System.out.println("Name is \"" + name + "\"");
        }
    }

If you want to know the cause of this issue take a look at this link1 and link2

Community
  • 1
  • 1
Abdelhak
  • 8,161
  • 4
  • 19
  • 34
0

This might be a better design to avoid duplicated code. Don't have to restrict the loop end condition to the while statement ;)

    try (Scanner sc = new Scanner(System.in)) {
        while (true) {
            System.out.print("Name: ");
            if (!sc.hasNextLine()) break;
            String name = sc.nextLine();
            System.out.println("Name is \"" + name + "\"");
        }
    }

EDIT: Your edit does not work correctly because sc.nextInt() is not eating the line feed, so put sc.nextLine() after the sc.nextInt().

Roy Wang
  • 10,260
  • 2
  • 13
  • 34