我正在编写一个非常基本的程序,但我遇到了一个问题。以下是我的代码片段(这是一个非常愚蠢的程序,不要试图猜测我用它做什么。)
System.out.println("Please press the Return button a 1000 times.");
for(int i = 1;i < 25;i++) {
input.nextLine();
}
System.out.println("Stop! Stop! Jeez, that was a joke! Do you think I'd make you press that button a 1000 times?");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
System.out.println("Let's move on.");
这里会发生的是程序要求用户按下返回按钮1000次,用户最终会开始发送垃圾邮件。主要的问题是,在我宣布这是一个笑话并且他只需要按下25次之后,我想要禁用用户输入,因为用户可能会按下多个按钮在意识到我只是在开玩笑之前。但是当thread.sleep运行时,用户输入仍处于活动状态,这会导致多个问题。
那么,有没有办法在程序休眠时禁用用户输入?
答案 0 :(得分:1)
您可以通过应用程序控制从控制台读取的内容。但完全禁用输入将取决于正在运行的环境应用程序的类型...例如。在cmd行中它不应该允许你在25进入后键入...而在像eclipse这样的IDE中,你可以在控制台上键入,但25行之后它不会被应用程序读取。
答案 1 :(得分:-1)
我相信在您的代码中添加1行就足够了(詹姆斯大建议):
>>> y = (3,4)
>>> z = [1,2]
>>> [x + y if isinstance(x, Iterable) else (x, ) + y for x in z]
[(1, 3, 4), (2, 3, 4)]
>>> y = (3,4)
>>> z = [(1,2),(2,3)]
>>> [x + y if isinstance(x, Iterable) else (x, ) + y for x in z]
[(1, 2, 3, 4), (2, 3, 3, 4)]
>>> y = (3,4)
>>> z = [[1,1],[2,2]]
>>> y = [3,4]
>>> z = [[1,1],[2,2]]
>>> [x + y if isinstance(x, Iterable) else (x, ) + y for x in z]
[[1, 1, 3, 4], [2, 2, 3, 4]]
>>> y = (3,4)
>>> z = [[1,1],[2,2]]
>>> [tuple(x) + y if isinstance(x, Iterable) else (x, ) + y for x in z]
[(1, 1, 3, 4), (2, 2, 3, 4)]
答案 2 :(得分:-1)
看看这个:
public class Main {
private static final String QUIT = "quit";
private static final int COUNT = 1000;
public static void main(String[] args) throws InterruptedException {
new Main(new BufferedReader(new InputStreamReader(System.in))).main();
}
private final BufferedReader in;
private final BlockingQueue<String> lines = new ArrayBlockingQueue<>(1);
private volatile boolean ignore;
public Main(BufferedReader in) {this.in = in;}
private void main() throws InterruptedException {
Thread inputReader = new Thread(this::read, "input-reader");
inputReader.setDaemon(true);
System.out.println("Please press the Return button a "+COUNT+" times.");
inputReader.start();
String line = "";
for(int i = 1;i <= 25;i++) {
line = lines.take();
System.out.println("Good! You entered '"+line+"'. Only "+(COUNT-i)+" left.");
}
System.out.println("Stop! Stop! Jeez, that was a joke! Do you think I'd make you press that button a "+COUNT+" times?");
ignore = true;
Thread.sleep(3000);
ignore = false;
String optionalLine = lines.poll();
if(optionalLine!=null) {
line = optionalLine; System.out.println("Ignored:" + line);
}
System.out.println("Let's move on. Type "+QUIT+" when you're tired.");
while(!QUIT.equalsIgnoreCase(line)){
line = lines.take();
System.out.println(">"+line);
}
System.out.println("Bye.");
}
private void read(){
try {
String line = in.readLine();
while(line!=null){
if (ignore) {
boolean inserted = lines.offer(line);
if (!inserted)
System.out.println("Ignored:" + line);
} else {lines.put(line);}
line = in.readLine();
}
} catch (IOException|InterruptedException e) {e.printStackTrace();}
}
}