I'm trying to make an application which copy an elevator operation (2 floors). But when I ask the user which floor he want to go, there are 2 differents possibilities. The first one, user enter a floor and the elevator move. The second one, after 10 secondes, still no response from user, at this point, the elevator have to close his door and turn off the light.
So my probleme is with the timeout, because I want my "while" to continue.
My main:
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)");
}
}
}
}
I try to use this solution: Time limit for an input
but I want to go back in my "while" and I don't know how to do it or if I'm using the right way to do it.
I also have some other class, Contoleur, Lumiere, Moteur, Porte, Bouton. But I haven't code the functions yet.
Thanks for you answer
EDIT
Ok I maybe find a way, I modify my code and now I have a function which take in parameter the scanner and a String:
public static int ask(Scanner sc, String t) {
System.out.println(t);
return sc.nextInt();
}
And I was wondering that maybe it's possible to put a timeout on a function. Do you know if it's possible ?