0

I have this code that asks for a name and age in a do-while loop:

public class Test1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        do  {
            System.out.print("Enter name & age: ");
            System.out.printf("%s %d",
                        scanner.next(), scanner.nextInt());
        } while (scanner.hasNext());
    }
}

It outputs:

Enter name & age: test 6
test 6

and then doesn't seem to react to my input, while it should have repeated the question on the third line. What is wrong here?

parsecer
  • 3,076
  • 4
  • 35
  • 78

2 Answers2

0

I think this should stop by the points it gets its input, since when you'll press enter, it would automatically enter the input and your method would end.

I would recommend you to use a while(true) statement if you want to have an infinite input. That issue shouldn't appear if you do it that way.

0

The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input. Read more

To avoid getting blocked by hasNext() you can simply pass true for loop condition.

import java.util.Scanner;
public class Test1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        do  {
            System.out.print("Enter name & age: ");
            System.out.printf("%s %d", scanner.next(), scanner.nextInt());
        } while (true);
    }
}
Lovesh Dongre
  • 926
  • 5
  • 18
  • It goes on an infinite loop. – Ashish Karn Jul 02 '20 at 04:11
  • Yes, it does. As per the requirement of this question and given code, it suggests that it requires an infinite loop. – Lovesh Dongre Jul 02 '20 at 04:15
  • Okay that fine, but what will be the use of such code. – Ashish Karn Jul 02 '20 at 04:29
  • This kind of code is generally used for a menu-driven program. The menu to be prompted repeatedly is written within a do while loop (You can use any other loop too but this is more logical since it is an entry controlled loop). I have seen people making small games like making user play Rock Paper Scissors with computer. – Lovesh Dongre Jul 02 '20 at 04:40