前言
两者都是获取其输入的字符串
但两者又有区别
next()只读取字符,直到遇到空格/Tab键/回车停止;
nextLine()只读取字符以及前后的的空格/Tab键,直到遇到回车键截止
实战代码
通过代码讲解区别使其更加深刻
import java.util.Scanner;
public class test01 {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
String s1=reader.nextLine();
String s2=reader.next();
System.out.println(s1);
System.out.println(s2);
}
}
可以看到如前言综述所讲到的那样
那么如果两者顺序返回来又会有不一样的效果
import java.util.Scanner;
public class test01 {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
//String s1=reader.nextLine();
String s1=reader.next();
String s2=reader.nextLine();
System.out.println(s1);
System.out.println(s2);
}
}
代码如图所示
可以看到next遇到空格后就断开
而nextline将其前面的也空格读取,直到遇到了回车才停止