package Month3;
import java.util.*;
public class Demo100914 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
/**
* sc.next()
* sc.nextLine()
* 这两个方法是Scanner类里的两个用于读取字符串的方法
*
* 对于一般的数据读取还行,但如果我们要读取的数据中间有一个回车(enter)那到底怎么读才算正确的呢?
*
* 比如输入 : aaa enter bbb
*/
//第一组
// String s = sc.next();
// String ss = sc.next();
// //第二组
// String s = sc.nextLine();
// String ss = sc.nextLine();
//第三组
// String s = sc.nextLine();
// String ss = sc.next();
//第四组
String s = sc.next();
// sc.nextLine();
String ss = sc.nextLine();
/**
* 其他都能搭配,但是就是第四组这俩不能搭配,要想搭配,必须在他们之间加上一个
* sc.nextLine()用于吃掉回车符
*
* 原理:
* next()会跳过字符串前面的 空格/enter/tab,直接读取字符串,
* 遇到空格/enter/tab结束,然后将剩下的(如果有enter)enter+字符串加入到缓存区
*
* nextLine()会这直接进行读取,不跳过 空格/enter/tab,直接读取一段字符串
* 遇到enter结束读取,然后将剩下的(如果有enter)字符串直接加入到缓存区,不带有enter,相当与将enter自动清除了
*
*/
//因此下面的代码就很好解释了:next()先读取了一个字符串aaa,然后将enter+后面的字符串bbb加入到缓存区里
//后面如果直接使用nextLine()来读取,他不像next()能跳过enter,相反遇到enter直接就结束了,导致根本读不到后面的有效字符,但是此时
//如果我们在中间加上nextLine(),遇到回车直接结束,并将bbb加入到缓存区,就不会影响下面nextLine()的读取了
//以上中间的的nextLine()的作用就相当于将回车符给吃了。
System.out.println(s);
System.out.println(ss);
}
}
java的next()和nextLine()区别
最新推荐文章于 2025-05-13 19:24:15 发布