我的java书有很多问题,其中一个问题在书的后面列出了正确的答案,我已经在下面写过。我明白每件事是怎么运作的。比如为什么你不想使用>=,当某些东西出现故障时它如何输出,等等。我只是不明白为什么for行要求它必须小于9,而不是<=9或<10。我知道最后一个数字不需要循环,因为在它被比较之前的那个数字,但是如果它小于9,它不会停止在第9个元素之前,使它永远不会被比较吗?
错误代码:
double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9};
for (int i = 1; i <= 10; i++)
if (scores[i] >= scores[i+1])
System.out.println(i + " and " + (i + 1)
+ " elements of score are out of order.");
正确的代码:
double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9};
for (int i = 1; i < 9; i++)
if (scores[i] > scores[i+1])
System.out.println(i + " and " + (i + 1)
+ " elements of score are out of order.");
编辑:问题是:以下是为了确保分数的元素是不降序的。但是,代码中存在错误。查找并更正错误。
发布于 2014-10-23 09:05:42
请记住,索引从0
开始。列表中有10个元素。这意味着索引的范围从0-9
开始。
您正在访问i
和i+1
元素。因此,在for
循环中,当i
为8
时,您将看到索引8
和9
处的项。如果让循环上升到9
,那么您将尝试访问索引9
和10
处的元素,并获得一个IndexOutOfBoundsException
。
发布于 2014-10-23 10:08:05
您需要从0到scores.length-2
对i
进行计数(因为length-1
是最后一个元素,并且您希望确保将倒数第二个元素与最后一个元素进行比较)。
或者,您可以从1..scores.length-1开始计数,并将索引i-1
与i
进行比较
double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9};
for (int i = 0; i <= scores.length - 2; i++)
if (scores[i] >= scores[i+1])
throw new RuntimeException(i + " and " + (i + 1) + " not strictly monotonic");
double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9};
for (int i = 1; i <= scores.length - 1; i++)
if (scores[i-1] >= scores[i])
throw new RuntimeException((i-1) + " and " + i + " not strictly monotonic");
发布于 2014-10-23 09:09:32
我不明白你想做什么。您应该从第0个索引开始循环,直到<= 9或<10。请始终记住,数组索引从0开始
https://stackoverflow.com/questions/26519646
复制相似问题