我如何摆脱这个无限循环

时间:2018-08-08 07:50:38

标签: while-loop infinite-loop

我正在尝试使该循环再次询问用户输入的不是1或2的内容,但是这使我陷入无限循环,我如何退出?

package vga;
import java.util.Scanner;
public class FPS_Info {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean placeHolder;
        String gameList[] = new String[2];
        gameList[0] = ("Battlefield 1");
        gameList[1] = ("Call Of Duty WWII");
        System.out.printf("Please slect from theses games %s or %s.%nType 1 for %s and type 2 for %s.%n", 
                            gameList[0], gameList[1], gameList[0], gameList[1]);
        int gameSelection = scanner.nextInt();
        if (gameSelection == 1 || gameSelection ==2) {
            placeHolder = true;
        }
        while (placeHolder = true) {
        if (gameSelection == 1) {
            System.out.println("Battlefield 1, good choice.");
            break;
            } else if (gameSelection == 2) {
            System.out.println("Call Of Duty WWII, good selection.");
            break;
            } else {
            System.out.println("Please enter one of the options."); 
            placeHolder = false;
            }
        }
    }

}

2 个答案:

答案 0 :(得分:0)

如果您重组代码,则不需要占位符。

import java.util.Scanner;

public class FPS_Info {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean placeHolder;
        String gameList[] = new String[2];
        gameList[0] = ("Battlefield 1");
        gameList[1] = ("Call Of Duty WWII");
        System.out.printf("Please slect from theses games %s or %s.%nType 1 for %s and type 2 for %s.%n",
                gameList[0], gameList[1], gameList[0], gameList[1]);

        int gameSelection = scanner.nextInt();
        while (gameSelection != 1 && gameSelection != 2) { // or while (gameSelection > 0 && gameSelection <= gameList.length)
            System.out.println("Please enter one of the options.");
            gameSelection = scanner.nextInt();
        }

        if (gameSelection == 1) {
                System.out.println("Battlefield 1, good choice.");
        }
        else if (gameSelection == 2) {
            System.out.println("Call Of Duty WWII, good selection.");
        }
    }
}

答案 1 :(得分:0)

您的代码包括:

while (placeHolder = true)

您可能是说placeHolder == true=分配true而不是对其进行检查,因此它并没有像您所希望的那样进行循环。

也就是说,没有理由首先== true。你可以

while (placeHolder)