nextLine和next都是读取输入台输入的字符。
next()只读取有效字符,不会读取有效字符前的空格、tab、回车,读取到有效字符后遇到空格、tab、回车才会停止读取。
nextLine()会读取字符前后的空格、tab,不管是在字符前还是后遇到回车都会停止读取,读取的是回车前的所有字符。
next()平时用的比较多,一般没什么问题,主要是nextLine(),以及nextLine()在next()后面使用时会出现错误。
1.nextLine()
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
System.out.println("s1:[" + s1 + "]");
System.out.println(s1.length());
只输入回车,此时nextLine读取回车前面字符,此时没有字符,所以s1长度为0。
2.next()和nextLine()
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.nextLine();
String s3 = sc.nextLine();
System.out.println("s1:[" + s1 + "]");
System.out.println("s2:[" + s2 + "]");
System.out.println("s3:[" + s3 + "]");
当nextLine()在next()后面使用时,next()读取有效字符遇到后面的回车键停止读取,而这个回车键会被接下来的nextLine()读取,所以s2此时没有读取到内容。
所以如果nextLine()在next()后面使用时,要多加一个nextLine()来读取next()留下来的回车键。
3. nextLine()和nextLine()
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
System.out.println("s1:[" + s1 + "]");
System.out.println("s2:[" + s2 + "]");
当两个nextLine()一起使用时,就不会出现2中的情况,所以可以用两个nextLine代替nextLine()+next()。