2015-03-08 94 views
-1

我正试图解决以下简单的编程练习:“编写一个程序,读取1到10之间的整数并计算每个整数的出现次数,假设输入以0结尾”。我提出了以下解决方案。我不熟悉调试器,并且最近3个小时尝试跟踪ArrayIndexOutOfBoundsException。也许有人能够看到ArrayIndexOutOfBoundsException发生在哪里?无法跟踪java.lang.ArrayIndexOutOfBoundsException:

import java.util.Scanner; 

public class Exercise07_03 { 
    /** Main method */ 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     int[] numbers = new int[10]; 
     System.out.print("Enter up to 10 integers between 1 and 10" + 
      "inclusive (input ends with zero): "); 

     int i = 0; 
     do { 
      numbers[i] = input.nextInt(); 
      i++; 
     } while (numbers[i] != 0 && i != 9); 

     displayCounts(countNumbers(numbers)); 
    } 

    /** Count the occurrences of each number */ 
    public static int[] countNumbers(int[] numbers) { 
     int[] counts = new int[10]; 

     for (int i = 0; i < counts.length; i++) 
      counts[numbers[i] - 1]++; 

     return counts; 
    } 

    /** Display counts */ 
    public static void displayCounts(int[] counts) { 
     for (int i = 1; i < counts.length + 1; i++) 
      if (counts[i - 1] != 0) 
       System.out.println(i + " occurs " + counts[i - 1] + " time"); 
    } 
} 
+0

ArrayIndexOutOfBoundsException通常发生在你在这里和那里有“一个”错误。如果您在调试程序中遇到问题,那么您可能需要在循环中进行一些打印调试,并确认您的索引实际上是您在任何时间点所认为的。 – orbitbot 2015-03-08 20:20:53

回答

1

问题是这里:

public static int[] countNumbers(int[] numbers) { 
    int[] counts = new int[10]; 

    for (int i = 0; i < counts.length; i++) 
     counts[numbers[i] - 1]++; 

    return counts; 
} 

的解决方案是在:

counts[(number - 1 > 0) ? number - 1 : 0]++; 

这用来检查(数字-1)大于零。如果不是,则使用0.如果为true,则使用数字-1。

+0

猜猜我其实说的是同样的事情,但恭维这一切;) – Mordechai 2015-03-08 20:51:20

+0

编号解释问题就是这么做的。我接着告诉他他的问题在哪里以及如何解决。 – lacraig2 2015-03-08 20:52:37

1
  counts[numbers[i] - 1]++; 

结果-1,如果输入包含0。