获取Array错误消息

时间:2014-03-09 22:42:48

标签: java arrays

我刚刚开始java编程,到目前为止我一直都做得非常好。因此,我遇到问题的程序只是在它经过之后才会出现错误消息,但程序按照我的意愿工作。 有问题的程序应该作为一个骰子1000次,并计算骰子的每一侧从1000推出多少次。它应该显示它,它做的。

这是我的程序:以及我在其下面的错误消息。感谢先进的任何帮助!

public class Test
{
     public static void main(String[] args)
     {//create array of 1,000 random numbers
         int[] randomNumbers = new int[1000];

         for(int i = 0; i < randomNumbers.length; i++)
             randomNumbers[i] =1 +(int)(Math.random() * 6);
         { //initialize count
             int[] counts = countInts(randomNumbers);
             displayIntCount(counts);
         }
     }

     public static int[] countInts(int[] ints)
     { //creat new array to hold occurence values
         int[] counts = new int[6];
         for(int i = 1; i <=counts.length; i++)
             for(int j=0;j<ints.length;j++)
                 if(ints[j] == i)
                     counts[i-1]++;  
         return counts;
     }

     public static void displayIntCount(int[] counts)
     {//display the occurrences
         for (int i = 0; i < counts.length; i++)
                 System.out.println("The number 1 occurs "+counts[i]+" times \nThe number 2 occurs "+counts[i+1]+" times \nThe number 3 occurs "+counts[i + 2]+ " times \nThe number 4 occurs " +counts[i+3]+ " times \nThe number 5 occurs " +counts[i + 4]+ " times \nThe number 6 occurs "+counts[i + 5]+ " times");
     }
} 

2 个答案:

答案 0 :(得分:2)

你在displayIntCount()中犯了错误,我为你做了改动:

public class Test
{
     public static void main(String[] args)
     {//create array of 1,000 random numbers
      int[] randomNumbers = new int[1000];

      for(int i = 0; i < randomNumbers.length; i++)
      randomNumbers[i] =1 +(int)(Math.random() * 6);
      { //initialize count
       int[] counts = countInts(randomNumbers);
       displayIntCount(counts);
      }
     }

    public static int[] countInts(int[] ints)
        { //creat new array to hold occurence values
         int[] counts = new int[6];
         for(int i = 1; i <=counts.length; i++)
             for(int j=0;j<ints.length;j++)
                 if(ints[j] == i)
                     counts[i-1]++;  
         return counts;
        }

     public static void displayIntCount(int[] counts)
      {//display the occurrences
         for (int i = 0; i < counts.length; i++)
             System.out.println("The number "+ (i+1) +" occurs "+counts[i]+ " times");
    } 
} 

数组中只有6个元素,运行6次后,你的索引用完了!

答案 1 :(得分:1)

为澄清,例外是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at Test.displayIntCount(Test.java:38) at Test.main(Test.java:20) Java Result: 1

问题发生在displayIntCount(),您使用i循环直到数组中的最后一个索引 - 然后尝试访问i+1i+5

可能因此希望将条件更改为counts.length-5。在这种情况下,似乎就像程序正常工作,因为异常导致它退出并且无法打印任何东西(因为这是一个你不应该打的情况所以不想打印无论如何,正常的输出保持不变。)