为什么我的数组循环超出范围?

时间:2013-11-04 02:48:20

标签: java arrays

代码从这里开始:

 System.out.print("Please enter number of rows: ");

  rows = keyboard.nextInt();  

      while(rows > MAX_ROWS || 0 > rows){
          System.out.print("ERROR: Out of range, try again: ");

          rows = keyboard.nextInt();


      }

      rowsTotal = new double[rows];
      positions = new double [rows][];

      for(index = 0; index < rowsTotal.length; index++){
          System.out.print("Please enter number of positions in row " + (char)(index+65) + " : ");
          pos = keyboard.nextInt();
          if(pos > MAX_POSITIONS){
              System.out.print("ERROR: Out of range, try again: ");
              pos = keyboard.nextInt();
          }
          positions[index] = new double[pos];


          }

      while(input != 'X'){    
      System.out.print("(A)dd, (R)emove, (P)rint,          e(X)it : ");

      input = keyboard.next().charAt(0);
      input = Character.toUpperCase(input);




      if(input == 'P'){
          for(int index1= 0; index1 < rowsTotal.length; index1++){
              System.out.print((char)(index1+65) + ":   " );

              for(int pos1= 0; pos1 < pos; pos1++){

                  **System.out.print(positions[index1][pos] + "  ");** 
              }
              System.out.print("[   " + totals + ", " + "   " + averages + "]");
              System.out.println();



      }

      }

错误消息如下:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at xxxxx.main(xxxxx.java:75)

这一行代码System.out.print(positions[index1][pos] + " ");

1 个答案:

答案 0 :(得分:1)

一旦你读完整个代码,答案就很简单 a)需要System.out.print(positions[index1][pos1] + " ");
b)“pos”是位置数组内LAST数组的大小。不是所有的都有相同的尺寸。因此,如果较早的数组较小(例如,如果输入1,2,3),则早期数组的超出范围。你必须将pos1循环到位置[index1] .length(所以将第73行更改为for(int pos1= 0; pos1 < positions[index1].length; pos1++)