1.next(nextInt)和nextline共同使用
next和nextline都是接收字符串,但是next遇到空格,tab,enter都会结束,而且不会接收这些空白字符
nextline()只有在遇到enter才会结束,并且会接收enter.
此时就引入来我们的第一个问题:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.nextLine();
System.out.print(s1+" "+s2);
}
可以发现我们在输入next之后就结束了,当next(nextInt)和nextLine连用的时候,next不会接收enter,此时ernter还留在sc中,如果下一次输入还是用next的话,也会跳过enter继续接收后面的字符串.
但是下一次如果是nextLine的话,他就会接收上一个enter进而直接结束本次输入.
遇到此种情况,我们可以在中间加一个sc.nextLine()专门用来接收空格,此时代码正常
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
sc.nextLine();
String s2 = sc.nextLine();
System.out.print(s1+" "+s2);
}
2.多个next(nextInt)的使用出现的问题
多个next的使用,next中是不能有空格的.这种情况经常出现在我们输入一个文件路径的时候,如果是以next输入一定要保证没有空格.如果有空格输入不会结束.但是next在接收的时候就会出现问题
第一个next接收到空格处停止,而第二个next就会继续接收到enter停止,这就会导致我们输入的文件路径出现问题,从空格处一分为二,还会导致下一次输入直接无效.