【问题标题】:how do i get out of this Infinite loop我如何摆脱这个无限循环
【发布时间】:2019-01-15 09:37:08
【问题描述】:

我试图让这个循环再次询问用户输入的不是 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;
            }
        }
    }

}

【问题讨论】:

  • 我写了一个答案,指出了while (placeHolder = true) 的问题,但我不能 100% 确定你试图实现什么逻辑。如果您更详细地解释您希望代码做什么,这可能会有所帮助。
  • 语言标签请
  • 你有一个严重的错字,分配给循环变量而不是检查是否相等。

标签: while-loop infinite-loop


【解决方案1】:

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

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.");
        }
    }
}

【讨论】:

    【解决方案2】:

    您的代码包括:

    while (placeHolder = true)
    

    您的意思可能是placeHolder == true。 = 分配 true 而不是检查它,所以它没有像你可能的意思那样循环。

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

    while (placeHolder)
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多