2016-08-15 84 views
0

如何在Java中等待输入?Java扫描器中断等待输入

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

我想创建while循环,你可以输入一些东西5分钟。 5min后应循环休息。但是当剩下时间时,循环不会再做,但扫描​​仪仍在等待输入并进入。

我想退出等待输入,我并不意味着断开while循环。

+6

http://stackoverflow.com/questions/5853989 /时间限制为输入 – ma3stro

+0

@ ma3stro,看起来像重复的好吧 –

回答

-1

试试这个

import java.util.Scanner;

import java.util.concurrent。*;

公共类扫描{

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.... 
} 

}

+0

我觉得这太难了。 'System.exit(0)'就是我想要的。 – Magnus2005

+0

不,它不退出程序....但是解决该问题的类在最后一次执行后没有运行代码....这就是发生了什么 – Positive

+0

上面所有的类都是当时间终止等待经过或终止循环时,值进入....这是对这个问题的回应...对不起,如果这是误导 – Positive

0

如果我正确理解你的问题,这是你想要什么:

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