BufferedInputStream 和 Scanner 有什么不同啊?
------解决方案--------------------
Scanner使用起来更加方便
Scanner不象BufferedInputStream那样需要显式的去catch IO异常
------解决方案--------------------
要真正弄懂两者间的区别,请看代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ScannerAndBufferedReader {
static void scannerTest(){
boolean flag = false;
Scanner sc = new Scanner(System.in);
do{
System.out.print( "Please input a: ");
try {
int a = sc.nextInt();
if(a < 0 || a > 9){
flag = true;//数据非法时,循环
}else{//数据合理就打印数据并退出循环
flag = false;
System.out.println( "a : " + a + "\nover! ");
}
} catch (Exception e) {
flag = true;//数据非法时,循环
System.out.println( "Scanner:Error data! ");
}
}while(flag);
}
static void bufferedReaderTest(){
boolean flag = false;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do{
System.out.print( "Please input a: ");
try {
int a = Integer.parseInt(br.readLine().trim());
if(a < 0 || a > 9){
flag = true;
}else{
flag = false;
System.out.println( "a : " + a + "\nover! ");
}
} catch (Exception e) {
flag = true;
System.out.println( "BufferedReader:Error data! ");
}
}while(flag);
}
public static void main(String[] args) {
ScannerAndBufferedReader.bufferedReaderTest();
// ScannerAndBufferedReader.scannerTest();
}
}
从控制台输入非法数据——字母时的情况:
一.使用Scanner:
Please input a:h
Please input a:Scanner:Error data!
Please input a:Scanner:Error data!
Please input a:Scanner:Error data!
Please input a:Scanner:Error data!
Please input a:Scanner:Error data!
……(无限循环了)
二.使用BufferedReader:
Please input a:k
BufferedReader:Error data!
Please input a:5
a :5
over!
看出区别来了吧!两者的读入机制有区别的。虽然Scanner可以不用进行显示的声明异常,但是遇到非法的用户输入时程序就直接退出去了。这在实际的用户程序中是不行的,也就是说容错处理不好!所以建议还是用BufferedReader吧!----iycrh