简体   繁体   English

运行时错误Java

[英]Runtime error Java

I am a beginner in Java and I have a run time error question. 我是Java的初学者,并且遇到运行时错误问题。 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: 有人可以解释一下为什么B是问题的正确答案,谢谢:

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()? 假设列表不为null,那么关于printAll()的调用,下列哪一项是正确的?

a)A run-time error occurs only if the list is empty. a)仅当列表为空时,才会发生运行时错误。

b)A run-time error occurs only if the list is not empty. b)仅当列表不为空时,才会发生运行时错误。

c)A run-time error never occurs. c)永远不会发生运行时错误。

d)A run-time error always occurs. d)总是发生运行时错误。

e)A run-time error occurs whenever the list has an even length e)只要列表长度为偶数,就会发生运行时错误

consider list have 10 items, then indexes were 0 - 9 考虑列表有10个项目,则索引为0-9

now when index=9 现在,当index = 9时

while loop check it 9<10 which is true and enters in then add 1 while循环检查9 <10是否为真,然后输入然后加1

index become 10 which is out of bound error occured 索引变为10,超出范围时发生错误

while (index < list.size) {
 index = index + 1;
 System.out.println(list.get(index));
}

Here index is incremented before accessing the list. 访问列表之前, index在此递增。 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. 如果列表为空,则条件while (index < list.size)将失败,因此,导致运行时错误的循环代码将永远不会执行。

Although not relevant to your question, the correct code would be to increment the index after reading: 尽管与您的问题无关,正确的代码是在阅读后增加index

while (index < list.size) {
 System.out.println(list.get(index));
 index = index + 1;
}
while (index < list.size) {
 index = index + 1;
 System.out.println(list.get(index));
}

case 1 情况1

: if list is empty, content of while loop will never be executed. :如果list为空,则while循环的内容将永远不会执行。

case 2 情况2

:if list is not empty, accessing last element will occurs an error. :如果列表不为空,则访问最后一个元素将发生错误。 Because the element at list.size is not there in list. 因为list.size的元素不在list中。

So, that error occurs only if list contains at least one element. 因此,仅当list包含至少一个元素时,才会发生该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM