为什么If语句与扫描程序保持循环

时间:2016-11-20 21:15:46

标签: java methods java.util.scanner infinite-loop

我的子类中有这个方法:

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: 

所以我的问题是,如何阻止此代码陷入无限循环?

1 个答案:

答案 0 :(得分:1)

displayOptions()在最后一行拨打displayOptions(),无线无限地呼叫displayOptions()等。