scanner的使用
scanner方法是java語言人機交互的重要方法。用於采集IO設備的信息輸入。
使用前需要先對scanner調用。
Scanner scanner = new Scanner(System.in);
調用之后一般會自動出現scanner包,如果不出現可以手動ALT+回車。

scanner的獲取方法有很多類型。
例如 next、nextLine、nextInt、nextDou等等
注意scanner方法不可獲取char類型。
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入文字:");
String s = scanner.nextLine();
System.out.println("接受的到的是:"+s);
System.out.println("=========================================");
System.out.println("請輸入文字:");
String v = scanner.next();
System.out.println("接受的到的是:"+v);
scanner.close();
第十行代碼需要格外注意。使用完scanner方法后需要關閉以節省內存!!
那next類型和nextLine類型有什么區別呢?
輸入同樣的文字,例如: Hello World !!
結果為

區別在於
next方法只能獲取空格之前的內容,空格之后的內容自動舍棄
nextLine方法可以獲取空格以及之后的內容,直到換行為止。
關於Scanner的進階用法
if(XXX.hasNext)用於判斷。如果有相應類型的數據輸入,那么執行if語句
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 1;
double f = 0.0;
System.out.println("請輸入一個數");
if (scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("整數數據:"+ i);
}
else{
f = scanner.nextDouble();
System.out.println("浮點數據:"+ f);
}
scanner.close();
}
