Harry Tan Harry Tan - 2 years ago 63
Linux Question

Keeps printing output in the Linux terminal until it reads an input

I am a newbie in Java and Object-oriented programming. Let's say I have created a 2d array game grid and initialized the array with characters, which looks like the following:


I want to update the ... with 123.
I have the following code:

while (true) {
if (....) map.printMap(); //what should be the condition here??
else ...dosomethingelse...;

My question is, does there exist a method which I can place in the if condition so that the grid will keeps printing by itself before an input 1? If it detects an input 1, it will stop printing at that moment, execute the else condition to update the grid, then print out as follows:


After that, it continues to keep printing the updated grid on screen, and follows the same pattern above until all of the ... are updated.

Any idea? Thanks in advance.

Answer Source

You can try something like the following:

try {
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader buf = new BufferedReader(reader);
    while (true) {
        if(!reader.ready()) {
        String command = buf.readLine();
        System.out.println("Command: " + command);
} catch(Exception e ){ 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download