Java java.lang.ArrayIndexOutOfBoundsException: 3 error message

5.3k Views Asked by At

So my code is working except when I was testing the method showSortedRows(). It showed me my desired output but at the same time gave me this error message. I don't really know why, please help me!

Error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Driver0.showSortedRows(Driver0.java:90)
at Driver0.choice(Driver0.java:35) at Driver0.main(Driver0.java:21)

import java.io.*;
import java.util.*;
public class Driver0
{
   public static int [][] array;
   public static int dimension1, dimension2;
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Welcome to Project 0.");
      System.out.println("What is the name of the data file? ");
      System.out.print("> ");
      String file = input.nextLine();
      readFile(file);
      String nextCommand = "";
      while (!(nextCommand.equals("quit"))) 
      {
         System.out.println("\nNext command");
         System.out.print("> ");
         nextCommand = input.nextLine();
         choice (nextCommand);
      }

   }

   public static void choice(String command) 
   {
      switch (command) 
      {
         case "help": System.out.println("show array\nwhich rows sorted\nwhich cols sorted"+
                                     "increase row i by n\nincrease col j by n\nquit\n");
                  break;
     case "show array": showArray();
                        break;
     case "which rows sorted": showSortedRows();
                               break;
     /*case "which cols sorted": showSortedCols();
     case "increase row i by n": increaseRow();
     case "increase col j by n": increaseCol();*/

      }
   }


    public static void readFile(String file)
    {
       try
       {
            Scanner sc = new Scanner(new File(file));
            dimension1 = sc.nextInt();
            dimension2 = sc.nextInt();
            array = new int[dimension1][dimension2];
            while (sc.hasNext()) 
            {
                for (int row = 0; row < dimension1; row++)
                {
                for (int column = 0; column < dimension2; column++) 
                {
                     array[row][column] = sc.nextInt();
                }
             }

            }
             sc.close();
          }

         catch(Exception e)
         {
             System.out.println("Error: file not found or insufficient       requirements.");
          }
          }
         public static void showArray() 
         {
              for (int rows = 0; rows < dimension1; rows++) 
              {
                    for (int col = 0; col < dimension2; col++) 
                    {
                         System.out.printf("%2d ", array[rows][col]);
                    }
                    System.out.println();
                 }
              }

             public static void showSortedRows()
             {
                  for (int rw = 0; rw < dimension1; rw++)
                  {
                      for (int cl = 0; cl < dimension2; cl++)
                      {
                         if (array[rw][cl] <= array[rw][cl+1])
                         System.out.printf("%2d,", rw);
                         rw++;
                      }
                      System.out.println();
                    }     

                 }

              }
3

There are 3 best solutions below

8
On

Your loop runs until cl < dimension2 so array[rw][cl+1] will cause the error.

You have to change your loop to for (int cl = 0; cl < dimension2-1; cl++)

8
On

It is this line:

if (array[rw][cl] <= array[rw][cl+1])

When cl is dimension2-1, cl + 1 causes an ArrayIndexOutOfBoundsException.

By the way, are you sure the rw++ within the double for loop is correct?
Is it supposed to be part of the if condition?
When dimension2 is > dimension1, it can also cause an ArrayIndexOutOfBoundsException.


showSortedRows() should be:

public static void showSortedRows() {
    for (int rw = 0; rw < dimension1; rw++) {
        boolean sortedRow = true;
        StringBuilder sb = new StringBuilder();
        for (int cl = 0; cl < (dimension2 - 1); cl++) {
            sb.append(array[rw][cl]).append(" ");
            if (array[rw][cl] > array[rw][cl + 1]) {
                sortedRow = false;
            }
            if((cl + 1) == (dimension2 - 1)) {
                sb.append(array[rw][cl + 1]).append(" ");
            }
        }
        if(sortedRow) {
            System.out.println("Row " + (rw + 1) + " is sorted!");
            System.out.println("Row contents: " + sb.toString());
        }
    }
}

Output:

Row 1 is sorted!
Row contents: 2 3 4 5 10 
Row 3 is sorted!
Row contents: -3 -1 0 1 5 
2
On

It is happening because of this line:

 if (array[rw][cl] <= array[rw][cl+1])  

Whats happening is that, when your variable cl becomes equal to dimension2 - 1 in the last iteration of the inner loop, it checks for the [cl][dimension2]th index. Which is not present in the array. Your array is of the size [row][dimension2] which means it counts from 0 to row - 1 for rows and 0 to dimension2 - 1 for columns. And still it is trying to access dimension2th index. And hence it gives you ArrayIndexOutOfBoundsException.

SOLUTION:

Your loop must be:

for(int cl = 0; cl < dimension2 - 1; cl ++)  

Hope this helps :)