import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ScannerTest {
public static Scanner sc = null;
// scanner是jdk1.5的工具類,在1.4中使用字符包裝流(BufferedReader)來讀取鍵盤輸入
// System.in是字節流,InputStreamReader是轉換流
// 與scanner的區別是,bufferedReader只能讀取String對象,不能讀取其他基本類型的輸入項
public static void fromKey0() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (br.readLine() != null) {
System.out.println("鍵盤輸入的內容:"+br.readLine());
}
}
// 從鍵盤輸入int,只會獲取鍵盤輸入的int類型,其他的類型不會打印
public static void fromKeyInt() {
sc = new Scanner(System.in);
while (sc.hasNextInt()) {
System.out.println("鍵盤輸入的內容:"+sc.nextInt());
}
}
// 從鍵盤輸入的內容,將空格等空白視為輸入項的分隔符
public static void fromKey() {
sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.println("鍵盤輸入的內容:"+sc.next());
}
}
// 修改分隔符為"\n",這樣除非輸入回車換行,否則會當作一個輸入項來處理
public static void fromKey1() {
sc = new Scanner(System.in);
sc.useDelimiter("\n");
while (sc.hasNext()) {
System.out.println("鍵盤輸入的內容:"+sc.next());
}
}
// 同樣的,scanner也可以從文件中讀取內容,nextLine()可以每次讀取一行,和上面設置分隔符為"\n"是同樣的效果
public static void fromFile() throws Exception {
sc = new Scanner(new File("c:\\bcmwl5.log"));
while (sc.hasNextLine()) {
System.out.println("文件中的內容:"+sc.nextLine());
}
}
public static void main(String[] args) throws Exception{
fromKeyInt();
//fromFile();
//fromKey();
//fromKey1();
}
}