我的子类中有这个方法:
public void displayOptions()
{
System.out.println("Sportscar driving options");
if (isOverheated())
System.out.println("WARNING: car is overheated.");
System.out.println("(c)ool off");
System.out.println("(d)rive normally");
System.out.println("(q)uit simulation");
System.out.print("Enter selection: ");
Scanner scanner = new Scanner(System.in);
String optionc = scanner.nextLine();
if (optionc.equals("c")){
System.out.println("all sport");
}
if (optionc.equals("d")) {
System.out.println("normal drive");
}
if (optionc.equals("q")) {
System.out.println("qutting simulation");
System.exit(0);
System.out.println("qutting simulation");
}
this.displayOptions();
}
这在我的主要方法中:
System.out.println("=== Sports car driving options ===");
Sports sportcar = new Sports((char) 0, null);
sportcar.displayOptions();
System.out.println("Move: ");
System.out.println("Sports: ");
正如你所看到的,它永远不会到达 Move: 和 Sports: system.out.print 行,因为即使在我输入它之后它仍然会循环:
Sportscar driving options
(c)ool off
(d)rive normally
(q)uit simulation
Enter selection:
所以我的问题是,如何阻止这段代码陷入无限循环?
最佳答案
displayOptions()
在最后一行调用 displayOptions()
,最后一行调用 displayOptions()
等等。
关于java - 为什么带有 Scanner 的 If 语句不断循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709477/