-2

I'm trying to create a loop that repeats itself till an eof command is entered. The loop works, but the first line of my loop is not being printed, and would only appear after I enter my first input.

This is what I have for my loop:

do {

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

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

    System.out.print("Vaccinated for chickenpox? ");
    vac = sc.nextBoolean();
    sc.nextLine();

    if (vac) {

    System.out.println("Vaccinated for chickenpox");
    numVac++;
    } else {

    System.out.println("Not vaccinated for chickenpox");
    }
} while (sc.hasNext());

Shouldn't the output be back to "Name: " after the if-else statement is printed out? However, nothing is printed out till I enter another keyboard input, and the next line I would see is "Name: Name is "a""

1 Answers1

0

Try flushing the PrintStream:

do {
    System.out.print("Name: ");
    System.out.flush();
    // ... etc.
markspace
  • 9,246
  • 2
  • 20
  • 35