运行时错误 Java [英] Runtime error Java
问题描述
我是 Java 初学者,我有一个运行时错误问题.我已经正确回答了,但是我并不完全理解答案背后的概念.谁能解释一下为什么B是这个问题的正确答案,谢谢:
I am a beginner in Java and I have a run time error question. I have answered it correctly, however I do not completely understand the concept behind the answer. Could someone please explain why B is the right answer to the question, thank you:
考虑以下声明:
private ArrayList<String> list;
...
public void printAll()
{
int index = 0;
while (index < list.size) {
index = index + 1;
System.out.println(list.get(index));
}
}
假设 list 不为 null,关于调用 printAll(),下列哪一项是正确的?
Assuming that list is not null, which one of the following is true about invocations of printAll()?
a)仅当列表为空时才会发生运行时错误.
a)A run-time error occurs only if the list is empty.
b) 仅当列表不为空时才会发生运行时错误.
b)A run-time error occurs only if the list is not empty.
c) 永远不会发生运行时错误.
c)A run-time error never occurs.
d) 总是会发生运行时错误.
d)A run-time error always occurs.
e)只要列表的长度为偶数,就会发生运行时错误
e)A run-time error occurs whenever the list has an even length
推荐答案
while (index < list.size) {
index = index + 1;
System.out.println(list.get(index));
}
这里 index
在访问列表之前增加.所以它每次都提前读取一个元素.所以当列表不为空时运行时出错.
Here index
is incremented before accessing the list. So it reads one element ahead everytime. So run-time error when the list is not empty.
如果列表为空,则条件 while (index
If the list is empty then the condition while (index < list.size)
will fail and hence the loop code that causes the run-time error will never be executed.
虽然与您的问题无关,但正确的代码是在阅读后增加 index
:
Although not relevant to your question, the correct code would be to increment the index
after reading:
while (index < list.size) {
System.out.println(list.get(index));
index = index + 1;
}
这篇关于运行时错误 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!