-1

Hello I am a beginner programmer and I have tried various different methods to get my code to work, but all of them have failed. I would be very thankful if someone could show me what it wrong with my code and how to fix the arrayindexoutofboundsexception error. Thank you so much in advance!!!

Here is my code:

public static void main(String[] args) {
        // TODO code application logic here

        // getting the number of rows and columns for the maze from the user 
        Scanner scanner = new Scanner(System.in);
        System.out.print("How many rows are in the maze? ");
        int rows = scanner.nextInt();
        int[][] maze = new int[rows][];
        System.out.print("How many columns are in the maze? ");
        int columns = scanner.nextInt();
        maze[rows] = new int[columns];

        // getting the data/danger levels for each row from the user 
        for (int c = -1; c < maze[rows].length; c++) {
            System.out.print("Enter the danger in row " + (c + 1) + ", " + "separated by spaces: ");
            maze[rows][c] = scanner.nextInt();
        }
        System.out.println(maze[rows][columns] + "\n");
    }
}
Christian Will
  • 1,529
  • 3
  • 17
  • 25

3 Answers3

1

intial value for c variable is -1. so when you do this

maze[rows][c] = scanner.nextInt();

you get the error since -1 index doesn't exists.

Change it to

maze[rows][c+1] = scanner.nextInt();
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

You start loop-counter c at value -1, but array starts with index [0]. The loop increment (c++ as last argument in for-loop) is executed at the end of each loop iteration, not at its beginning.

Christoph Bimminger
  • 1,006
  • 7
  • 25
0

The problem is this line:

maze[rows] = new int[columns];

Arrays in Java are 0-indexed, so if I create a maze with 3 rows, the last index is 2. What you want is this:

maze[rows - 1] = new int[columns]

A quick note that you can debug simple programs very quickly in an IDE like IntelliJ Idea by setting breakpoints and seeing the execution of your program step-by-step: debugging-with-intellij

Nate Vaughan
  • 3,471
  • 4
  • 29
  • 47