我正在尝试制作一个复制电梯操作(2层)的应用程序。但是当我问用户他想去哪一层时,有两种不同的可能性。第一次,用户进入一个楼层,电梯就会移动。第二个,10秒后,仍然没有用户的响应,在这一点上,电梯不得不关上门和关灯。
所以我的问题是超时,因为我想让我的"while“继续。
我的主要内容:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class TP5 {
private String floorAsk = "";
TimerTask task = new TimerTask() {
public void run() {
if (floorAsk.equals("")) {
System.out.println("No response ...");
task.cancel();
}
}
};
public boolean getInput() throws Exception {
Timer timer = new Timer();
timer.schedule(task, 10 * 1000);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
floorAsk = in.readLine();
timer.cancel();
System.out.println("Floor ask " + floorAsk);
return true;
}
/**
* main.
* @param args ceci est un String[]
*/
public static void main(String[] args) {
Controller c = new Controller();
Door p = new Door();
Light l = new Light();
Engine m = new Engine();
Button b = new CallButton();
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("What is your floor ?");
String actualFloorString = sc.nextLine();
int actualFloor = Integer.parseInt(actualFloorString);
if (actualFloor == 0 || etageAct == 1) {
System.out.println("You are at floor " + actualFloorString);
if (actualFloor != c.getShaft()) {
if (actualFloor > c.getShaft()) {
m.up();
} else if (actualFloor < c.getShaft()) {
m.down();
}
}
if (!l.isOn()) {
l.on();
}
if (!p.isOpen()) {
p.open();
}
System.out.println("Which floor do you want to go ?");
try {
(new TP5()).getInput();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("test");
} else {
System.out.println("Please enter a valid floor (0 or 1)");
}
}
}
}我尝试使用这个解决方案:Time limit for an input
但我想回到我的"while“状态,我不知道该怎么做,或者我是否使用了正确的方法。
我还有一些其他的课程,Contoleur,Lumiere,Moteur,Porte,Bouton。但是我还没有对函数进行编码。
谢谢你的回答
编辑
好吧,我可能会找到一种方法,我修改了我的代码,现在我有一个函数,它接受参数,扫描器和一个字符串:
public static int ask(Scanner sc, String t) {
System.out.println(t);
return sc.nextInt();
}我在想,也许可以给一个函数设置一个超时。你知道这是否可能吗?
发布于 2019-02-22 23:32:25
我建议使用Timer类。https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
在10秒超时后,让计时器调用一个“关闭”电梯门的方法。
如果用户输入有效的整数,则可以取消计时器。当门打开时,可以创建新的计时器。
编辑:我没有看到您已经在使用Timer对象,因为我被向下滚动到main方法。
https://stackoverflow.com/questions/54829288
复制相似问题