前言
大家都知道next()与nextLine()比较大的区别是用next()不能得到带空格的字符串,而nextLine()可以。
但是大家在使用next()和nextLine()方法有没有遇到过以下问题,比如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String s1 = sc.next();
System.out.print("请输入第二个字符串:");
String s2 = sc.nextLine();
System.out.println(s1);
System.out.println(s2);
}
}
而且nextInt(),nextDouble()等等都会遇到和next()一样的问题,以下例子:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数数字:");
int s1 = sc.nextInt();
System.out.println("请输入一个字符串:");
String s2 = sc.nextLine();
System.out.println(s1);
System.out.println(s2);
}
}
类似原因都是是输入第一个内容摁下回车后导致nextLine()自动接收Enter作为结束符,直接默认将第二个字符串内容置为空。解决方法也很简单,就是输入第二个内容之前提前再使用nextLine()将这个回车符吸收掉,如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个字符串:");
String s1 = sc.next();
System.out.println("请输入第二个字符串:");
sc.nextLine();
String s2 = sc.nextLine();
System.out.println(s1);
System.out.println(s2);
}
}
到此我们可以知道,nextLine()在读取内容的时候,是以读取到Enter结束的,但是它只会返回Enter以前的内容,Enter会被吸收读取但是不会作为内容返回。以下例子:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个字符串:");
String s1 = sc.nextLine();
System.out.println("请输入第二个字符串:");
String s2 = sc.nextLine();
System.out.println(s1);
System.out.println(s2);
}
}