解决Java中nextInt()之后的nextLine()读取不到键盘输入的问题

今天做某题的时候老是编译错误,输入的内容还没写完,就提示错误了。
想着可能输入这块有什么问题,最后查百度得知:

当用nextInt()读取缓冲区数据时,遇到回车或者空格,数据就会被读取走,但是回车符或者空格会被留下。当再调用nextLine()时,因为nextLine()是以回车符结束,当被调用后,刚好缓冲区还有被nextInt()“吃”剩下的回车符,所以还没等接着输入第二个参数,nextLine()就已经结束。从而导致后序程序出现异常。

int m = sc.nextInt();  
int n = sc.nextInt();  
char [][]table = new char[n][];
for(int i=0;i<n;i++)
	table[i] = sc.nextLine().toCharArray();

将以上代码加一句sc.nextLine()就行了,这是为了吃掉上面输入数据剩下的回车符。
修改后

int m = sc.nextInt();  
int n = sc.nextInt();  
sc.nextLine();
char [][]table = new char[n][];
for(int i=0;i<n;i++)
	table[i] = sc.nextLine().toCharArray();
发布了54 篇原创文章 · 获赞 63 · 访问量 5882

猜你喜欢

转载自blog.csdn.net/S_123789/article/details/104392006