一、System.in
使用System.in獲取控制檯上輸入的信息,每次只能讀取一個字節的數據。利用數組緩衝也可以讀取字符串。
package Practice;
public class ReaderConsole {
public static void main(String[] args) {
try{
System.out.println("請輸入字符串:");
//數組來緩衝
byte[] b = new byte[5];
//讀取數據
int n = System.in.read(b);
//轉換爲字符串
String s = new String(b,0,n);
System.out.println("輸入的字符串爲:" + s);
}catch(Exception e){}
}
}
當我輸入數據123456時,控制檯顯示:輸入的字符串爲12345,有最後一位6沒有讀取到。這是因爲我在設置了用來緩衝數據的數組大小爲5,即byte[] b = new byte[5];
所以這種方法是有弊端的,使用時要特別注意。
二、Scanner
使用Scanner可以獲取控制檯上的字符串。Scanner類中一些常用的方法:
(1)next()方法獲取一個以space,tab或enter結束的字符串。
(2)nextInt()方法,將獲取的字符串轉換成整型。
(3)nextFloat()方法,將獲取的字符串轉換成浮點型。
(4)nextBloolean方法,將獲取的字符串轉換成布爾類型。
(5)nextLine()方法,獲取輸入的一行字符串(此方法與BufferedReader中的沒有太大區別)
用法:
Scanner sc=new Scanner(System.in);
String s=sc.next();
三、BufferedReader
用法:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
String read = null;
System.out.print("請輸入數據:");
try {
read = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("輸入的數據爲:"+read);
}catch(Exception e){}