Java – How to write method which performs when user presses only Enter

consoleinputjava

I want to write infinity while statement which will perform every time when user just presses Enter. Every stream readers I know perform when user enteres anything into console or presses Enter twice.


I want to write something like this:

Console:
output 1 [enter have been pressed onse]
output 2 [enter have been pressed onse]
output 3 [enter have been pressed onse]
[so on…]

This is my current code:

addQuestionsInArray();

Random r = new Random();
DataInputStream is = new DataInputStream(System.in);
while (true) {
    String question = questionsList.get(r.nextInt(questionsList.size()));
    System.out.println(question);
    if (String.valueOf(is.readInt()).equals("0")) {
        break;
    }
}

Best Solution

To wait for the user to hit enter, I usually do something like

new Scanner(System.in).nextLine();

Demo:

import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        System.out.println("Press enter.");
        new Scanner(System.in).nextLine();
        System.out.println("Thanks.");
    }
}

Output:

Press enter.
[enter]
Thanks.

Regarding your edit, I still suggest you use a Scanner. (DataInputStream should be used for binary data, not strings and characters written on System.in):

Scanner s = new Scanner(System.in);

while (true) {
    String question = questionsList.get(r.nextInt(questionsList.size()));
    System.out.println(question);

    String input = s.nextLine();
    // int input = s.nextInt();    if you want integers

    if (input.equals("0"))
        break;

    // if (input == 0) break;      if you want integers
}
Related Question