Java的Scanner類介紹
阿新 • • 發佈:2018-11-21
Scanner類的介紹
介紹:一個可以使用正則表示式來解析基本型別和字串的簡單文字掃描器。
- 構造方法:
- Scanner(InputStream sourse)
- System類下由一個靜態的欄位
- public static final InputStream in; 標準輸入流,對應鍵盤上輸入
- 一般方法:
- hasNextXxx() 判斷是否還有下一個輸入項,並且看輸入的是否滿足要求,如果滿足則返回true 否則返回false。
- nextXxx() 獲取下一個輸入值 一般用預設的空格 或者回車間隔
while(true){
Scanner input = new Scanner(System.in);
if(input.hasNextInt()){
return input.nextInt();
}else{
System.out.println("輸入格式錯誤");
}
}
Scanner類的問題
Scanner input = new Scanner(System.in);
System.out.println("輸入整數");
int x = input.nextInt();
System.out.println ("輸入字串");
String str = input.nextLine;
System.out.println(x+"...."+str);
/* 這裡會發現 沒有讓人輸入str就輸出了,而且輸出時str是空的,
* 這是為什麼呢?nextInt 在回車時截至了錄入 回車為(\r\n) 但在nextLine也是用回車結
* 尾的。當nextLine錄入時,直接遇見了(\r\n)
* 解決方法:1:重新創造一個物件Scannner,
* 2:先用 nextLine 錄入 在處理字串 將整數 分出來。