sc.next() 和 sc.nextLine 的区别
他们两个都是用来接收用户的输入,区别在于:
—— next() 从遇到第一个有效字符开始扫描,遇到第一个空格或换行符结束。
—— nextLine() 则是扫描剩下的所有字符串知道遇到回车为止。
举个例子,例如:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(sc.next());
}
显然,当我们使用 sc.next() ,在输入中有空格的时候,会结束输入接收。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextLine());
}
当我们使用 sc.nextLine() ,我们此时是按行接收的,会接收到一整行的输入。