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();
}
}
}
Your loop runs until
cl < dimension2
soarray[rw][cl+1]
will cause the error.You have to change your loop to
for (int cl = 0; cl < dimension2-1; cl++)