【发布时间】:2019-04-18 07:00:42
【问题描述】:
我不确定这是否可能,因为我还没有找到确切的答案,但 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();
}
}
}
}
【问题讨论】:
-
你能准确解释什么“不起作用”吗?没有错误消息或堆栈跟踪很难判断。
-
在
while循环内添加goodLine = lineNumber < 0 || lineNumber > 4;退出。 -
@secretsuperstar 这看起来是一个简单的解决方案,但它在概念上是错误的:你不能复制代码,即使它只是一行。因为您必须记住,当需要适应条件时,您必须更新支票的每个副本。复制代码始终是引入未来错误的第一步。
-
@dave 你是对的。我没有提到错误信息。它进入了一个无限循环。后来我删除了 if 条件,但这也没有帮助。
-
@GhostCat 谢谢你的笔记。我正在努力理解答案。 :) 我完全是个新手。我当然会接受其中一种解决方案。
标签: java while-loop boolean