Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a while to run until scanner get input?

I'm trying to write a loop which runs until I type a specific text in console where the application is running. Something like:

while (true) {
try {
    System.out.println("Waiting for input...");
    Thread.currentThread();
    Thread.sleep(2000);
    if (input_is_equal_to_STOP){ // if user type STOP in terminal
        break;
    }
} catch (InterruptedException ie) {
    // If this thread was intrrupted by nother thread
}}

And I want it to write a line each time it pass through so I do not want it to stop within the while and wait for next input. Do I need to use multiple threads for this?

like image 264
Xenovoyance Avatar asked Mar 28 '11 19:03

Xenovoyance


People also ask

How do you take input without a Scanner class?

Without the Scanner class, reading user input with System.in is more complicated, and instead uses the InputStreamReader to convert data from bytes to characters. To do this, you must pass Java's System.in to the constructor of an InputStreamReader, and then pass that to the BufferedReader.


1 Answers

Do I need to use multiple threads for this?

Yes.

Since using a Scanner on System.in implies that you're doing blocking IO, one thread will need to be dedicated for the task of reading user input.

Here's a basic example to get you started (I encourage you to look into the java.util.concurrent package for doing these type of things though.):

import java.util.Scanner;

class Test implements Runnable {

    volatile boolean keepRunning = true;

    public void run() {
        System.out.println("Starting to loop.");
        while (keepRunning) {
            System.out.println("Running loop...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        System.out.println("Done looping.");
    }

    public static void main(String[] args) {

        Test test = new Test();
        Thread t = new Thread(test);
        t.start();

        Scanner s = new Scanner(System.in);
        while (!s.next().equals("stop"));

        test.keepRunning = false;
        t.interrupt();  // cancel current sleep.
    }
}
like image 55
aioobe Avatar answered Sep 22 '22 21:09

aioobe