简体   繁体   中英

Why is my array looping out of bounds?

Code starts here:

 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();



      }

      }

Error Message as Below:

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

which is this line of code System.out.print(positions[index1][pos] + " ");

Answer is simple once you read the whole code.
a) It needs to be System.out.print(positions[index1][pos1] + " ");
b) "pos" is the size of the LAST array inside the positions array. BUt not all of them have the same size. So if earlier arrays are smaller (for example if you entered 1,2,3), than the earlier arrays run out of bounds. You have to loop pos1 to positions[index1].length (so change line 73 to for(int pos1= 0; pos1 < positions[index1].length; pos1++) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM