原文地址:https://blog.csdn.net/u014717036/article/details/52227782
java.util.Scanner类是一个简单的文本扫描类,它可以解析基本数据类型和字符串。它本质上是使用正则表达式去读取不同的数据类型。
Java.io.BufferedReader类为了能够高效的读取字符序列,从字符输入流和字符缓冲区读取文本。
下面是两个类的不同之处:
当nextLine()被用在nextXXX()之后,用Scanner类有什么问题
尝试去猜测下面代码的输出内容;
1 // Code using Scanner Class
2 import java.util.Scanner;
3 class Differ
4 {
5 public static void main(String args[])
6 {
7 Scanner scn = new Scanner(System.in);
8 System.out.println("Enter an integer");
9 int a = scn.nextInt();
10 System.out.println("Enter a String");
11 String b = scn.nextLine();
12 System.out.printf("You have entered:- "
13 + a + " " + "and name as " + b);
14 }
15 }
Input:
50 Geek
Output:
Enter an integer Enter a String You have entered:- 50 and name as
让我们尝试使用BufferReader类,并且使用相同的输入
1 // Code using BufferedReader Class
2 import java.io.*;
3 class Differ
4 {
5 public static void main(String args[])
6 throws IOException
7 {
8 BufferedReader br = new BufferedReader(new
9 InputStreamReader(System.in));
10 System.out.println("Enter an integer");
11 int a = Integer.parseInt(br.readLine());
12 System.out.println("Enter a String");
13 String b = br.readLine();
14 System.out.printf("You have entered:- " + a +
15 " and name as " + b);
16 }
17 }
Input:
50
Geek
Output:
Enter an integer Enter a String you have entered:- 50 and name as Geek
在Scanner类中如果我们在这任何7个nextXXX()方法之后调用nextLine()方法,这nextLine()方法不能够从控制台读取任何内容,并且,这游标不会进入控制台,它将跳过这一步。这nextXXX()方法是这些方法,nextInt(),nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next()。
在BufferReader类中就没有那种问题。这种问题仅仅出现在Scanner类中,由于nextXXX()方法忽略换行符,但是,nextLine()并不忽略它。如果我们在nextXXX()方法和nextLine()方法之间使用超过一个以上的nextLine()方法,这个问题将不会出现了;因为nextLine()把换行符消耗了。可以参考这个程序的正确写法。这个问题和C/C++中的scanf()方法紧跟gets()方法的问题一样。
其他的不同点:
原文链接:Difference between Scanner and BufferReader Class in Java
翻译:crane-yuan
[ 转载请保留原文出处、译者和译文链接。]
——————— 本文来自 crane-yuan 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/u014717036/article/details/52227782?utm_source=copy
转载于:https://www.cnblogs.com/mumu122GIS/p/9718102.html
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/101398.html原文链接: