我的java程序无法正常运行.

Pan*_*pai 1 java arrays variables while-loop

我是一个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!");
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,它会正确读取名称,但它不会显示任何文本,例如"你有几个朋友......"或"你很善于交际!" 此外,当我运行它时,在第三个和第四个名称之间说"线程中的异常"主"java.lang.ArrayIndexOutOfBoundsException:8".我不知道我的代码有什么问题,但如果有人能告诉我这个问题,我将不胜感激.谢谢.

ζ--*_*ζ-- 5

while (x <= 8) {
   System.out.println("Frind number " + (x + 1) + " is " + facebookFriends[x]);
   x++;
}
Run Code Online (Sandbox Code Playgroud)

试图最终阅读facebookFriends[8].这是不可能的,因为它从0到7.

使用:

while (x < facebookFriends.length) {
Run Code Online (Sandbox Code Playgroud)

代替.

  • 更好的是`while(x <facebookFriends.length)`.不要使用魔术数字. (4认同)