【发布时间】:2013-07-29 07:40:42
【问题描述】:
我是一个java初学者,我写了这段代码:
class Friends {
public static void main(String[] args) {
String[] facebookFriends = { "John", "Joe", "Jack", "Lucy", "Bob", "Bill", "Sam", "Will" };
int x = 0;
while (x <= 8) {
System.out.println("Frind number " + (x + 1) + " is " + facebookFriends[x]);
x++;
}
System.out.println("");
if (facebookFriends.length < 5) {
System.out.println("Where are all you're friends?");
}
else if (facebookFriends.length == 5) {
System.out.println("You have a few friends...");
}
else {
System.out.println("You are very sociable!");
}
}
}
当我运行程序时,它会正确读取名称,但不会显示任何文本,例如“你有几个朋友......”或“你很善于交际!”此外,当我运行它时,它在第三个和第四个名称之间显示“线程“主”java.lang.ArrayIndexOutOfBoundsException:8 中的异常”。我不知道我的代码有什么问题,但如果有人能告诉我问题,我将不胜感激。谢谢。
【问题讨论】:
-
一个数组从 0 到 length-1 你必须这样做
while(x < 8)因为你的长度是 8 -
第三次和第四次之间不会出现错误。你在最后一个之后得到错误。只是在标准输出流上打印第四个错误流之前打印了错误流。在每个
System.out.println(...)之后,您可以执行System.out.flush()(刷新意味着现在打印而不是在缓冲区已满时打印)来查看此效果。
标签: java arrays variables while-loop