运行时错误的Java [英] Runtime error Java
问题描述
我在Java初学者,我有一个运行时错误的问题。我已经回答正确了,但我不完全理解的答案背后的概念。可能有人请解释为什么B是正确答案的问题,谢谢:
考虑以下声明:
私人的ArrayList<串GT;清单;
...
公共无效printAll()
{
INT索引= 0;
而(指数<则为list.size){
指数=指数+ 1;
的System.out.println(list.get(指数));
}
}
假设列表不为空,下列哪一个是真实的约printAll()?
的调用a)仅当列表为空时,会发生运行时错误。
B)仅当列表不为空,出现运行时错误。
c)一个运行时错误永远不会发生。
d)一个运行时错误总是发生。
E)每当列表有偶数长度发生运行时错误
而(指数<则为list.size){
指数=指数+ 1;
的System.out.println(list.get(指数));
}
下面首页
递增的前的访问列表。因此,它读取一个元素提前每次。因此,运行时错误当列表不是空的。
如果列表为空则条件而(指数<则为list.size)
将失败,因此环code,导致运行时错误将永远不会被执行。
虽然您的问题不相关的,正确的code将递增首页
读后:
而(指数<则为list.size){
的System.out.println(list.get(指数));
指数=指数+ 1;
}
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:
Consider the following declarations:
private ArrayList<String> list;
...
public void printAll()
{
int index = 0;
while (index < list.size) {
index = index + 1;
System.out.println(list.get(index));
}
}
Assuming that list is not null, which one of the following is true about invocations of printAll()?
a)A run-time error occurs only if the list is empty.
b)A run-time error occurs only if the list is not empty.
c)A run-time error never occurs.
d)A run-time error always occurs.
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));
}
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.
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.
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屋!