java - 电梯:用户输入
问题描述
我正在尝试制作一个复制电梯操作(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)");
}
}
}
}
我尝试使用此解决方案:输入的时间限制
但我想回到我的“时间”,我不知道该怎么做,或者我是否使用正确的方法来做。
我还有其他课程,Contoleur、Lumiere、Moteur、Porte、Bouton。但我还没有编写函数代码。
谢谢你的回答
编辑
好的,我可能会找到一种方法,我修改了我的代码,现在我有了一个函数,它接收扫描仪参数和一个字符串:
public static int ask(Scanner sc, String t) {
System.out.println(t);
return sc.nextInt();
}
我想知道也许可以对函数设置超时。你知道这是否可能吗?
解决方案
我建议使用 Timer 类。 https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
10 秒超时后,让计时器调用“关闭”电梯门的方法。
如果用户输入一个有效的整数,定时器可以被取消。门打开时可以创建一个新的计时器。
编辑:当我向下滚动到主要方法时,我没有看到您已经在使用 Timer 对象。
推荐阅读
- firebase - 在 Firebase 中缓存
- jquery - 将 .click 转换为单击 jquery ajax
- arrays - swift:不能在不可变值上使用变异成员:下标是 get-only
- python - Repl.it DB 429 客户端错误:对 url 的请求过多(Python)
- python - 让网络用户输入代表公式的代码的安全方法是什么?
- google-chrome-extension - Chrome 92 升级中的 ExtensionSidebarPane 是否损坏?
- android - Flutter Firestore 未在已发布的 android apk 中检索任何数据
- javascript - React-native 构建失败 RCTCxxBridge.mm 正常 x86_64 目标 c+
- jquery - 通过函数内部的ajax获取变量(Jquery)
- ruby-on-rails - 尝试在生产中运行rails控制台时如何修复“spring不是捆绑包的一部分”