我不确定这是否可能,因为我还没有找到确切的答案,但 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();
}
}
}
}
最佳答案
这里:
boolean goodLine = lineNumber < 0 || lineNumber > 4;
计算一次,并将结果分配给该变量。
稍后对 lineNumber = scan.nextInt();
进行更改,不更改该 boolean 变量!
“正确”的解决方案:您必须重新计算 boolean 属性。但理想情况下不是通过复制代码,而是通过创建一个小的辅助方法:
boolean isGoodLine(int lineNumber) { return lineNumber < 0 || lineNumber > 4; }
现在,您只需在 lineNumber 更改时调用该方法即可,而不是在其他代码中使用 boolean 变量!
关于java - 我可以给 boolean 基元一个条件作为初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53314987/