我正在为MIT的Java入门课程的作业7工作。任务是建立一个Magic Squares评估员。我的代码工作正常,但我不明白为什么在评估输入文件的中途,IF语句的执行顺序翻转(根据我在Eclipse中的控制台输出)。
for (String part : parts) {
try {
sum += Integer.parseInt(part);
sum2 = otherChecks.get(itemNumber) + Integer.parseInt(part);
otherChecks.set(itemNumber, sum2);
if (itemNumber == rowNumber){
sum2 = otherChecks.get(otherChecks.size()-2) + Integer.parseInt(part);
otherChecks.set(otherChecks.size()-2, sum2);
System.out.println("diag forward " + part +" item and row numbers " + itemNumber + ","+ rowNumber);
}
if (itemNumber == parts.length - rowNumber - 1 ){
sum2 = otherChecks.get(otherChecks.size()-1) + Integer.parseInt(part);
otherChecks.set(otherChecks.size()-1, sum2);
System.out.println("diag backward " + part +" item and row numbers " + itemNumber + ","+ rowNumber);
}
itemNumber++;
} catch (NumberFormatException err) {
System.out.println("Skipping Line");
sum = lastSum;
rowNumber --;
}
}
这是读入java的文件:
8 58 59 5 4 62 63 1
49 15 14 52 53 11 10 56
41 23 22 44 45 19 18 48
32 34 35 29 28 38 39 25
40 26 27 37 36 30 31 33
17 47 46 20 21 43 42 24
9 55 54 12 13 51 50 16
64 2 3 61 60 6 7 57
输出。行跳过是没有数字的行,它会抛出一个异常,正如输出中的“跳过行”所示。
diag forward 8 item and row numbers 0,0
diag backward 1 item and row numbers 7,0
Skipping Line
diag forward 15 item and row numbers 1,1
diag backward 10 item and row numbers 6,1
Skipping Line
diag forward 22 item and row numbers 2,2
diag backward 19 item and row numbers 5,2
Skipping Line
diag forward 29 item and row numbers 3,3
diag backward 28 item and row numbers 4,3
Skipping Line
diag backward 37 item and row numbers 3,4
diag forward 36 item and row numbers 4,4
Skipping Line
diag backward 46 item and row numbers 2,5
diag forward 43 item and row numbers 5,5
Skipping Line
diag backward 55 item and row numbers 1,6
diag forward 50 item and row numbers 6,6
Skipping Line
diag backward 64 item and row numbers 0,7
diag forward 57 item and row numbers 7,7
并解释这一点,我看到我的假设失败了。感谢评论中的Hot Licks。 谢谢,抱歉
答案 0 :(得分:1)
它处于循环中。如果你在调试器中运行它,你会看到它跳过第一个中的项目" if"并在某些情况下转到第二个。它仍在遍历循环。在" part"上设置手表它应该更清楚。
请注意,您可能会被低估,因为这更像是一个学校问题而不是通常适用于Stack Overflow。