【Java】next() 与 nextLine() 区别及nextLine方法吞回车的解决方法

next() 与 nextLine() 区别

next():

1、一定要读取到有效字符后才可以结束输入。以空格、回车、Tab键都会视为结束符。
2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。

next() 不能得到带有空格的字符串。

nextLine():

1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。

2、可以获得空白。

问题

假如你要读取以下数据
详见问题请看[蓝桥杯2019初赛]人物相关性分析

20
This is a story about Alice and Bob. Alice wants to send a private message to Bob.


一开始我是这样做的

Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.nextLine();

然后调试的时候结果只给了我一个0,后来发现它把空格当成字符串读进去了

解决方法

Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();//提前吞掉空格,防止后面吞掉
String s = in.nextLine();

猜你喜欢

转载自blog.csdn.net/weixin_45867159/article/details/114162058