0

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.

1
  • 2
    You might want to look into something like JCurses for continuously-updated terminal window applications. Commented Jun 11, 2016 at 23:47

2 Answers 2

1

I would use two threads for this:

  • Thread 1 periodically (?) updates the screen until a flag is set.
  • Thread 2 uses a blocking read on console input to get input from the user, and then sets the flag when appropriate.

You could also attempt to do this by calling the available() method, but the specified semantics of that method are such that it is hard (impossible?) to use it portably; i.e. without relying on behavior of the console input stack that could vary from one OS to another.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Stephen, can you provide a code example for your suggestion?
Nope. Try reading the Java tutorial stream on threads and concurrency: docs.oracle.com/javase/tutorial/essential/concurrency
0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.