next()方法使用:
我们知道,next()方法在读取到空白符(Space键 , enter键 , tab键)时就结束,但这是有前提的:即next()方法一定要读取到有效字符后才可以结束. 如果在有效字符之前录入了空白符的话,next()方法会将这些空白符"过滤"掉,直接从有效字符开始读取. 举个例子:
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一句话:");
String str=sc.next();
System.out.println(str);
sc.close();
}
}
运行结果如下图:
可以看到,即使你在输入有效字符之前狂按tab键或enter键或space键,next()方法还是从有效字符之处开始读取!
当next()方法读取到有效字符之后,倘若再出现空白符的话,next()就将其视作结束符.
nextLine()方法使用:
我们知道,nextLine()方法的结束符只是enter键,所以用它来读取录入数据的话是可以得到带有空格的字符串的.
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一句话:");
String str=sc.nextLine();
System.out.println(str);
sc.close();
}
}
另外值得注意的是:nextLine()方法返回的是enter键之前所有的字符,包括空字符.
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一句话:");
String str=sc.nextLine();
System.out.print(str);
sc.close();
}
}
可以看到,我们在键盘上什么都不录入,直接敲enter键,可以看到nextLine()方法还有能读取且输出.
总结
Scanner是一个扫描器,我们录入到键盘的数据,先存到缓存队列中等待读取.