我可以给布尔基元一个条件作为初始化吗?

时间:2018-11-15 08:14:50

标签: java while-loop boolean

我不确定是否有可能,因为我没有找到确切的答案,但是NetBeans没有给出错误。但是,如果可能的话,为什么我的代码不起作用?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int[][] fiveMatrix = {
        {1, 4, 7, 5, 3}, {3, 7, 9, 10, 1}, {4, -3, 2, -4, 1}, {5, 9, 6, 4, 3}, {1, 2, 3, 4, 5},};

    System.out.print("Which line do you want to write out (0-4)? ");
    int lineNumber = scan.nextInt();
    boolean goodLine = lineNumber < 0 || lineNumber > 4;
    if (goodLine) {
        while (goodLine) {
            System.out.println("Bad index.");
            System.out.print("Which line do you want to write out (0-4)? ");
            lineNumber = scan.nextInt();
        }
    }
}

}

4 个答案:

答案 0 :(得分:3)

这里:

boolean goodLine = lineNumber < 0 || lineNumber > 4;

被评估一次,并将结果分配给该变量。

后来对lineNumber = scan.nextInt();进行的更改不会更改该布尔变量!

“正确”的解决方案:您必须重新计算boolean属性。但理想情况下,不是通过复制代码,而是通过创建一个小的辅助方法:

boolean isGoodLine(int lineNumber) { return lineNumber < 0 || lineNumber > 4; }

现在,您只要在lineNumber更改时就调用该方法即可,而不必在其他代码中包含布尔变量!

答案 1 :(得分:1)

您可能想更新循环中的布尔值,以避免无限循环。

boolean badLine = lineNumber < 0 || lineNumber > 4;
while (badLine) {
    System.out.println("Bad index.");
    System.out.print("Which line do you want to write out (0-4)? ");
    lineNumber = scan.nextInt();
    badLine = lineNumber < 0 || lineNumber > 4;
}

我重命名了boolean,因为它的原始名称令人困惑。我也消除了if条件,因为它是多余的。

答案 2 :(得分:1)

您在while循环中缺少一行

boolean goodLine = lineNumber < 0 || lineNumber > 4;

考虑重构为避免重复代码的方法:

public boolean goodLine(Scanner scan) {
    System.out.print("Which line do you want to write out (0-4)? ");
    int lineNumber = scan.nextInt();
    return lineNumber < 0 || lineNumber > 4;
}

并命名为:

while(goodLine());

考虑到它也称为badLine,因为用户输入错误(不是0-4值)

答案 3 :(得分:0)

代码简化且易于理解

import java.util.Scanner;

public class Post3 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int[][] fiveMatrix = {
            {1, 4, 7, 5, 3}, {3, 7, 9, 10, 1}, {4, -3, 2, -4, 1}, {5, 9, 6, 4, 3}, {1, 2, 3, 4, 5},};

        System.out.println("Which line do you want to write out (0-4)? ");
        int input = -1;
        while(true) {
            System.out.println("input valid number between 0 to 4");
            input = scan.nextInt();
            if(input >= 0 && input <= 4) {
                break;
            }
        }
        System.out.println("input is "+input);
        scan.close();

    }

}