DanielDC88
DanielDC88

Reputation: 21

Press Enter to Continue Skipping subsequent

I'm trying to make a program wait for the user to press a key before continuing multiple times. Preferrably, this would be any key, but I'm not too fussed if the user can only press Return/Enter to continue.

import java.io.IOException;
import java.util.Scanner;

public class test {
    public static void main(String[] args) throws IOException {
        System.out.print("1");
        System.in.read();
        System.out.print("2");
        System.in.read();
        System.out.print("3");
    }
}

The desired output is as such:

1

After the first press:

1
2

After the second press:

1
2
3

In reality what happens is this:

1

After the first press:

1
23

As you can see, it skips all subsequent indications to wait for a user input.

I've also tried using a scanner, and that works, but it allows the user to enter the text as well, which is something I'd prefer not to happen.

Upvotes: 1

Views: 747

Answers (1)

Keppil
Keppil

Reputation: 46209

You can use the skip() and available() methods to discard the data before the next read():

System.out.print("1");
System.in.read();
System.in.skip(System.in.available());
System.out.print("2");
System.in.read();
System.out.print("3");

Upvotes: 4

Related Questions