Java读取迷宫TXT文件触发ArrayIndexOutOfBoundsException异常求助
迷宫读取代码数组越界异常修复
需求:从TXT文件读取迷宫,文件首行是迷宫的行数和列数,下方为迷宫内容(1代表墙,0代表通路),但运行代码时抛出数组越界异常。
迷宫内容
9 7 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 0 1 1 1 0 1 1
原Java代码
import java.io.*; import java.util.*; public class Thiseas{ public static void main(String[] args) throws IOException{ File mazeFile = new File("C:/Users/Kristi/Desktop/project/sample_input.txt"); BufferedReader read = new BufferedReader(new FileReader(mazeFile)); String rea = read.readLine(); String[] split = rea.split(" "); int width = Integer.valueOf(split[0]); int height = Integer.valueOf(split[1]); String readline; readline = read.readLine(); int num = 0; char[][] maze1 = new char[width][height]; while((readline = read.readLine()) != null){ char[] ch = readline.toCharArray(); for(int i = 0; i < ch.length; i++){ maze1[i][num] = ch[i]; } num++; } for (int i = 0; i < width; i++){ for (int j = 0; j < height; j++){ System.out.print(maze1[i][j]+' '); } System.out.println(); } } }
抛出的异常信息
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 9 out of bounds for length 9
at Thiseas.main(Thiseas.java:19)
问题分析
- 数组维度与赋值顺序颠倒:首行的9是行数,7是列数,你定义的
maze1是char[width][height]即char[9][7](9行7列),但赋值时用了maze1[i][num],把列索引放在行的位置,行索引放在列的位置,逻辑完全错误。 - 读取行包含空格导致长度溢出:直接把每行转成
char[]会包含空格,比如一行"1 1 1 0 1 1 1"转成char数组后长度是13(7个数字+6个空格),循环时i会遍历到12,远超过数组列数7,直接触发越界。 - 多余读取跳过第一行迷宫内容:代码里提前执行了
readline = read.readLine();,导致while循环直接跳过了第一行迷宫数据。
修正后的代码
import java.io.*; public class Thiseas{ public static void main(String[] args) throws IOException{ File mazeFile = new File("C:/Users/Kristi/Desktop/project/sample_input.txt"); BufferedReader read = new BufferedReader(new FileReader(mazeFile)); // 读取首行,解析行数和列数 String[] sizeInfo = read.readLine().split(" "); int rows = Integer.parseInt(sizeInfo[0]); int cols = Integer.parseInt(sizeInfo[1]); char[][] maze = new char[rows][cols]; int currentRow = 0; String line; while((line = read.readLine()) != null){ // 按空格拆分每行的数字,过滤空字符串(兼容首尾空格) String[] nums = line.split("\\s+"); for(int col = 0; col < cols; col++){ // 把数字字符存入对应行列位置 maze[currentRow][col] = nums[col].charAt(0); } currentRow++; } // 打印验证迷宫 for (int i = 0; i < rows; i++){ for (int j = 0; j < cols; j++){ System.out.print(maze[i][j] + " "); } System.out.println(); } read.close(); } }
修正点说明
- 把
width和height改成rows和cols,语义更清晰,避免混淆行和列。 - 读取每行时用
split("\\s+")拆分数字,自动忽略多个空格,只获取有效数字字符串。 - 赋值时按
maze[currentRow][col]的顺序,对应行和列的正确逻辑。 - 去掉多余的
readline = read.readLine();,确保读取所有迷宫行。 - 增加关闭流的操作,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Fear de Beard ____
相关产品推荐
相关产品推荐

