2017-10-21 127 views
-1

你好,我是一名初学者程序员,我尝试了各种不同的方法让我的代码工作,但都失败了。如果有人能告诉我我的代码有什么问题,以及如何解决arrayindexoutofboundsexception错误,我将非常感激。非常感谢你提前!为什么我的代码给了我一个ArrayIndexOutOfBoundsException?

这里是我的代码:

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"); 
    } 
} 

回答

1

c变量的初始值为-1。 所以当你做到这一点

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

你的错误,因为-1指数不存在。

将其更改为

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

您在值-1开始循环计数器C,但数组索引[0]开始。循环增量(C++作为for循环中的最后一个参数)在每次循环迭代结束时执行,而不是在其开始处执行。

0

的问题是这一行:

maze[rows] = new int[columns]; 

数组在Java中是0指数的,所以如果我创建3行的迷宫,最后指数是2你需要的是这样的:

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

快速注释,您可以通过类似的IntelliJ IDEA的IDE非常快速调试简单的程序设置断点并逐步查看程序的执行情况: debugging-with-intellij

相关问题