Javaでの入力待ちを中断する方法はありますか?Javaスキャナが入力を中断するのを中断しました
Scanner s = new Scanner() ;
s.nextInt();
//here break without input
ループを作成したい場所に5分間入力します。 5分後にループが壊れるはずです。しかし時間が残っていると、ループはやり直しませんが、スキャナはまだ入力を待っています。
私は入力を待つのをやめたいと思っています。
Javaでの入力待ちを中断する方法はありますか?Javaスキャナが入力を中断するのを中断しました
Scanner s = new Scanner() ;
s.nextInt();
//here break without input
ループを作成したい場所に5分間入力します。 5分後にループが壊れるはずです。しかし時間が残っていると、ループはやり直しませんが、スキャナはまだ入力を待っています。
私は入力を待つのをやめたいと思っています。
インポート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....
}
}
私はそれが難しいと思います。 'System.exit(0)'はこれが私が望むものです。 – Magnus2005
いいえ、それはプログラムを終了していません....しかし、その問題を解決するクラスは、最後の実行後に実行するコードがありません....それは起こったのです – Positive
上記のすべてのクラスは、値が入力されたときに経過したか、ループを終了します....質問に応答している...申し訳ありませんが、それは誤解を招く – Positive
私が正しくあなたの質問を理解していれば、これはあなたが望むものである:
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);
}
}
}
http://stackoverflow.com/questions/5853989 /入力制限時間 – ma3stro
@ ma3stro、それは重複しているように見える –