【问题标题】:My java program won't run properly.我的 java 程序无法正常运行。
【发布时间】: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 &lt; 8) 因为你的长度是 8
  • 第三次和第四次之间不会出现错误。你在最后一个之后得到错误。只是在标准输出流上打印第四个错误流之前打印了错误流。在每个System.out.println(...) 之后,您可以执行System.out.flush()(刷新意味着现在打印而不是在缓冲区已满时打印)来查看此效果。

标签: java arrays variables while-loop


【解决方案1】:

while (x &lt;= 7) 而不是while (x &lt;= 8)

Java 中的数组,从 0 开始,而不是 1。

如果您查看异常:

“线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常: 8"

它告诉你出了什么问题。

【讨论】:

  • 在我看来,通常对于数组,使用i&lt;length 比使用i&lt;=(length-1) 更好,因为它的可读性略高。
  • 对,我更喜欢那个,不知道为什么我用这个:)
【解决方案2】:
while (x <= 8) {
   System.out.println("Frind number " + (x + 1) + " is " + facebookFriends[x]);
   x++;
}

尝试最终读取facebookFriends[8]。这是不可能的,因为它是从 0 到 7。

用途:

while (x < facebookFriends.length) {

改为。

【讨论】:

  • while (x &lt; facebookFriends.length) 更好。不要使用幻数。
【解决方案3】:

x &lt;= 8 应该是x &lt; 8

facebookFriends 数组有 8 个元素(索引从 07)。尝试访问超出此范围的任何位置都会导致ArrayIndexOutOfBoundsException 异常。

【讨论】:

  • 非常感谢!我不敢相信我没有看到!
【解决方案4】:

正如其他人已经指出的那样,它应该是 x &lt;= 7x &lt; 8 或更好的 x &lt; facebookFriends.length,因为 Java 数组是从零 (0) 开始的。

另一种编写代码的方式是:

class Friends 
{
    public static void main(String[] args)
    {
        String[] facebookFriends = { "John", "Joe", "Jack", "Lucy", "Bob", "Bill", "Sam", "Will" };

        int length = facebookFriends.length;
        int num = 1;
        for ( String friend: facebookFriends )
            System.out.println("Friend number " + (num++) + " is " + friend);

        System.out.println("");

        if (length < 5)
            System.out.println("Where are all your friends?");
        else if (length == 5)
            System.out.println("You have a few friends...");
        else
            System.out.println("You are very sociable!");
    }    
}

【讨论】:

    【解决方案5】:

    如果你真的想让它通用 而(x

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多