java的nextInt()和nextLine()混用的报错问题

代码

	 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));
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值