今天用
Scanner
和BufferedReader
分别输入时发现用Scanner
for 循环会自动跳过一次,然后还不知道为什么
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
// int n=Integer.parseInt(scanner.nextLine());
int n=scanner.nextInt();
for (int i = 0; i < n; i++) {
String str=scanner.nextLine();
System.out.println(str);
}
}
用scanner.nextInt();
输出
输出结果:
4
111
111
222
222
333
333
如果用 int n=Integer.parseInt(scanner.nextLine());
,那么就没有换行
输出结果:
4
111
111
222
222
333
333
444
444
这样会发现 ,scanner.nextInt()
和 scanner.nextLine()
处理机制不一样:
用 nextInt()
处理,我们在输入 4 按下空格后,会将 4 和 空格‘\r’ 存入缓存区,返回时返回 4,但是‘\r’会继续存在缓存区里面,在我们for循环时用scanner.nextLine() 读取时,发现缓存区里面有“\r”,那么跳过输入,直接将“\r”赋值给 str,然后在控制台输出换行。
用nextLine()
处理,会将 4 和 空格‘\r’ 存入缓存区,返回时返回 4,去除掉“\r”,那么在我们for循环时用scanner.nextLine() 读取时,会发现没有东西,就会让我们在控制台输入。
这就是为什么用nextInt()
时会莫名其妙出现一个换行。
解决办法:
用scanner.nextLine()
替代scanner.nextInt()
int n=Integer.parseInt(scanner.nextLine());
或者
不用Scanner
而用BufferedReader
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(input.readLine());
for (int i = 0; i < n; i++) {
String str=input.readLine();
System.out.println(str);
}
}