最常见的就是 while(sc.hasNext()){ int a = nextInt(); } int都是很好读的,最主要是char:

1. 基础读取方式

如果字符串中不包含空格,可以使用 next() 方法:

Java

Scanner in = new Scanner(System.in);
int n = in.nextInt();      // 读取字符串长度
String s = in.next();      // 读取字符串(遇到空格或换行符停止)

2. 处理带空格的字符串

如果字符串中可能包含空格,或者你需要读取一整行,应使用 nextLine()。但要注意,在 nextInt() 之后使用 nextLine() 时,需要先用一个额外的 nextLine() 消耗掉数字后的换行符:

核心原因

Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();             // 消耗掉整数后的换行符
String s = in.nextLine();  // 读取整行字符串

核心方法对比: