Runtime error Java

依然范特西╮ 提交于 2019-12-11 23:18:52

问题


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


回答1:


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;
}



回答2:


consider list have 10 items, then indexes were 0 - 9

now when index=9

while loop check it 9<10 which is true and enters in then add 1

index become 10 which is out of bound error occured




回答3:


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

case 1

: if list is empty, content of while loop will never be executed.

case 2

:if list is not empty, accessing last element will occurs an error. Because the element at list.size is not there in list.

So, that error occurs only if list contains at least one element.



来源:https://stackoverflow.com/questions/16638349/runtime-error-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!