【发布时间】:2019-02-22 14:30:22
【问题描述】:
我正在尝试制作一个复制电梯操作(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
但我想回到我的“虽然”,但我不知道该怎么做,也不知道我是否使用了正确的方法。
我还有一些其他的课程,Contoleur、Lumiere、Moteur、Porte、Bouton。但我还没有编写函数代码。
谢谢你的回答
编辑
好吧,我可能会找到一种方法,我修改了我的代码,现在我有了一个函数,它接收扫描仪参数和一个字符串:
public static int ask(Scanner sc, String t) {
System.out.println(t);
return sc.nextInt();
}
我想知道也许可以对函数设置超时。不知道有没有可能?
【问题讨论】:
-
你的代码如果翻译成英文会更好理解。
-
对不起,我翻译一下
-
尝试实例化一个布尔值。并将该布尔值用于您的 while 语句。这样你就可以退出并回到你的 while 循环中。您可以使用 TimerTask 将布尔值设置为 true/false
-
不起作用,10 秒后,我只收到消息“无响应 ...”(我在循环后添加打印)但似乎不影响程序跨度>
-
有人知道是否有办法回到循环中,或者是否有其他方法?