Cody
Cody

Reputation: 890

Java - Loop while keeping another code running

I'm not sure how to accomplish this. I want to have a timer which would keep a loop on forever but while that loop is running I want to be able to have a Scanner running and waiting for user input. Basically like a chat. Where the loop would constantly check for any new messages posted but while the loop is running the user can still submit messages.

How can I do this?

Also I dont have a GUI setup yet. This is all running in a simple command prompt (if it matters).

Upvotes: 2

Views: 423

Answers (4)

Luke Dowell
Luke Dowell

Reputation: 177

You could use a multiple thread application, however it seems to me that would be a bit more complicated than what your looking for.

: Try just defining a timer, and adding a timertask to it, and then taking in input in a loop:

    Scanner scan = new Scanner(System.in);
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            //Do whatever you want with your messages here
        }
    }, 0, 1000);

    //Wait for user input
    while(true) {
        String bar = scan.next();
    }

Upvotes: 1

jefflunt
jefflunt

Reputation: 33954

Well, sounds pretty early stage, but you could either do multiple Threads, or you could just have your loop bounce back and forth between new messages from the user, and checking to see if there are new things posted.

If you're reading from an InputStream (or one of its sub-classes) you can call the available method to check and see if the number of available bytes if > 0 (if there is anything to be read from either the other chat participants, or the user input).

So, a loop:

  • if (newMessages) ...post the new messages...
  • if (newUserChat) ...send new message out...

That's basically all there is to it.

Upvotes: 0

lobster1234
lobster1234

Reputation: 7779

You can have a thread running which is waiting for the input. Once the input is entered, the main program can call a method in the thread which can then decide whether to terminate the loop or keep going.

Upvotes: 0

Related Questions