Harry Tan Harry Tan - 5 months ago 10
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:

+++++
+1..+
+++++


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

You can try something like the following:

try {
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader buf = new BufferedReader(reader);
    while (true) {
        map.printMap();
        if(!reader.ready()) {
            Thread.sleep(1000);
            continue;
        }
        String command = buf.readLine();
        System.out.println("Command: " + command);
    }
} catch(Exception e ){ 
    e.printStackTrace();
}