0

How to break waiting for input in Java?

        Scanner s = new Scanner() ;
        s.nextInt();
        //here break without input

I want to create while loop where you can Input something for 5min. after 5min loop should be break. but when time is left, loop wont do again but scanner is still wait for input and enter.

I want to exit from waiting for input, I dont mean break while loop.

Magnus2005
  • 97
  • 3
  • 13

2 Answers2

1

If i correctly understand your question, this is what you want:

import java.util.Scanner;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Testes {
    public static void main(String[] args) throws Exception {
        try {
            while (true) {
                System.out.println("Insert int here:");
                Scanner s = new Scanner(System.in);

                FutureTask<Integer> task = new FutureTask<>(() -> {
                    return s.nextInt();
                });

                Thread thread = new Thread(task);
                thread.setDaemon(true);
                thread.start();
                Integer nextInt = task.get(5, TimeUnit.MINUTES);

                System.out.println("Next int read: " + nextInt + "\n----------------");
            }
        } catch (TimeoutException interruptedException) {
            System.out.println("Too slow, i'm going home");
            System.exit(0);
        }
    }
}
Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101
-1

Try This Out

import java.util.Scanner;

import java.util.concurrent.*;

public class Scan {

public static void main(String arg[]) throws Exception{
    Callable<Integer> k = new Callable<Integer>(){

        @Override
        public Integer call() throws Exception {
            System.out.println("Enter x :");
            return new Scanner(System.in).nextInt();
        }

    };
    Long start= System.currentTimeMillis();
    int x=0;
    ExecutorService l = Executors.newFixedThreadPool(1);  ; 
    Future<Integer> g;
    g= l.submit(k);
    while(System.currentTimeMillis()-start<10000&&!g.isDone()){

    }
    if(g.isDone()){
        x=g.get();
    }
    g.cancel(true);

    if(x==0){
        System.out.println("Shut Down as no value is enter after 10s"  );
    } else {
        System.out.println("Shut Down as X is entered "  + x );
    }
    //Continuation of your code here....
}

}

Positive
  • 62
  • 5
  • I think it is too difficult. 'System.exit(0)' is this what I wanted. – Magnus2005 Aug 15 '16 at 14:36
  • No, It is not exiting the program.... But the class that solves that problem has no code to run after the last execution.... That is what happened – Positive Aug 15 '16 at 14:42
  • All the class above does is to terminate the waiting when time elapsed or terminate the loop when value is entered.... Which is in response to the question... Sorry, if that is misleading – Positive Aug 15 '16 at 14:45