[英]Whats wrong with this my timer?
好的,所以我用这个计时器脚本完成了一半,但我注意到它运行功能第二次不再输入输入任何想法为什么? 它确实需要所有并在启动时等待输入
public class ManagingLifts {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Timer timer = new Timer();
DeliveryMan d = new DeliveryMan();
Hacker h = new Hacker();
Lift id = new Lift();
ArrayList<Person> p = new ArrayList();
ArrayList<String> who = new ArrayList();
int MINUTES = 2; // setting the duration of timer for people entering lift
timer.scheduleAtFixedRate(new TimerTask() // task to be run every 2 minute
{
@Override
public void run()
{
int counter = 0;
int HorD = (int)(Math.random() * 2) + 1; // decides who gets into the lift
if (HorD <= 1) //
{
System.out.println("What is your name?");
String name = sc.nextLine();
System.out.println("What is your NRIC?");
String nric = sc.nextLine();
System.out.println("What is your Country?");
String country = sc.nextLine();
System.out.println("What floor do you wan to go?");
int floor = sc.nextInt();
if(floor >=50) //making sure they only go to allowed floors
{
System.out.println("You can only access floors 40 - 50!");
}
Person list = new Person(name, nric);
p.add(list);
h.setCountry(country);
who.add("Hacker"); // to have a list of who entered the lift
counter = +2;
}
else if (HorD >= 2)
{
System.out.println("What is your name?");
String name2 = sc.nextLine();
System.out.println("What is your NRIC?");
String nric2 = sc.nextLine();
System.out.println("What type of food are you delivering?");
String food = sc.nextLine();
System.out.println("What floor do you want to go?");
int floor2 = sc.nextInt();
if(floor2 >=31)
{
System.out.println("You can only access floors 2 - 30!");
}
Person list2 = new Person(name2, nric2);
p.add(list2);
d.setTypeofF(food);
who.add("DeliveryGuy"); // who entered the lift
counter = +2;
}
if(counter > 200) // stop running lift after 200min
{
timer.cancel();
}
}
}, 0, 1000 * 60 * MINUTES); // will run this function every 2min
}
}
在读取楼层编号时,您只读取下一个int,而不是enter
以移动到下一行。 由于未读取,因此下次循环开始时, name
将为空字符串。
所以在读取地板时添加sc.nextLine()
,或者只是读取一个String并使用Integer.parseInt
将其转换为int。
或者,您也可以通过重新创建Scanner
来丢弃循环之间System.in
所有输入。 而不是在任务之外创建扫描程序,只需在任务运行时创建扫描程序(因此在run
方法中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.