代码
Scanner scan = new Scanner(System.in);
//在此输入您的代码...
int n = scan.nextInt();
int m = scan.nextInt();
char[][] chars = new char[n][m];
Queue<S> que = new LinkedList<>();
for(int i = 0;i<n;i++) {
String str = scan.nextLine();
chars[i]=str.toCharArray();
for(int j=0;j<m;j++) {
if(chars[i][j]=='g') {
que.add(new S(i,j));
}
}
}
报错
4 5
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
at 遍历.长草.main(长草.java:29)
问题原因
代码在读取输入时出现了 ArrayIndexOutOfBoundsException 异常,是因为 Scanner 的 nextInt() 和 nextLine() 的混用导致输入读取错位。以下是问题的原因和解决方法:
问题原因
nextInt() 不消耗换行符:
当你调用 scan.nextInt() 读取 n 和 m 后,输入缓冲区中会留下一个换行符 \n。
接下来的 scan.nextLine() 会直接读取这个换行符,导致 str 是一个空字符串 “”。
因此,str.toCharArray() 返回空数组,而 chars[i] = str.toCharArray() 会抛出 ArrayIndexOutOfBoundsException(因为 chars[i] 的长度是 m,而空数组无法填充)。
这里具体问题是:
nextInt() 读取 4 和 5 后,缓冲区剩余 \n。
第一个 scan.nextLine() 读取 \n,导致 str 为空。
后续循环中 str 会错位读取。
解决方法
常用方法 :在 nextInt() 后调用 nextLine() 消耗换行符
int n = scan.nextInt();
int m = scan.nextInt();
scan.nextLine(); // 消耗换行符
char[][] chars = new char[n][m];
Queue<S> que = new LinkedList<>();
for (int i = 0; i < n; i++) {
String str = scan.nextLine();
chars[i] = str.toCharArray();
for (int j = 0; j < m; j++) {
if (chars[i][j] == 'g') {
que.add(new S(i, j));
}
}
}