一、Scanner用法
Java中使用Scanner獲取輸入流,常見寫法爲
Scanner s=new Scanner(System.in); //實例化Scanner類,取系統的輸入
String str=s.next() //獲取控制檯輸入的有效字符(空格之後不識別了)
//s.nextln(),獲取一行任意字符(包括空格)
//s.nextInt(),獲取整型,當輸入字符串是,會報錯
//at java.util.Scanner.nextInt(Unknown Source)
二、計算器加法功能
import java.util.Scanner;
public class temp{
public static void main(String[] args) {
double a,b;
System.out.println("請輸入第一個數字:");
a=GetDouble();
System.out.println("請輸入第二個數字:");
b=GetDouble();
System.out.println(a+"+"+b+"="+(a+b)); //如果不用(),系統會認爲是字符串連接,因爲a+b是寫在字符串後面,如果寫在前面,就先做加運算,不需要加括號
}
public static double GetDouble() {
double x;
try{
Scanner s=new Scanner(System.in);
x=s.nextDouble();
}catch (Exception e) {
// TODO: handle exception
System.out.println("輸入非法,請輸入數字:");
return GetDouble();
}
return x;
}
}
三、Sanner再學習
1、Scanner做爲輸入流封裝的類,輸入流可以從文件、內存、網絡中獲取。
2、然後又分爲字節流(InputStream)和字符流(Reader),字符流需要考慮編碼問題(中文gbk佔2個字節,utf8因爲是變長,佔3或4個字節)
3、處理文件
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
//使用正則表達式:s.useDelimiter(",\\s*");
//另一種寫法如下,兩種區別暫時還不懂,仔細學完IO流後再來分析
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}