Java Scanner 類詳解(附例子)學習
在筆試程式設計過程中,關於資料的讀取如果迷迷糊糊,那後來的程式設計即使想法很對,實現很好,也是徒勞,於是在這裡認真總結了Java Scanner 類的使用
通過 Scanner 類來獲取使用者的輸入,下面是建立 Scanner 物件的基本語法:
Scanner s = new Scanner(System.in); // 從鍵盤接收資料
接下來我們演示一個最簡單的資料輸入,並通過 Scanner 類的 next() 與 nextLine() 方法獲取輸入的字串,在讀取前我們一般需要 使用 hasNext 與 hasNextLine 判斷是否還有輸入的資料:
next() 與 nextLine() 區別
next()的使用方法演示:
-
import java.util.Scanner;
-
public class scannertest {
-
public static void main(String[] args) {
-
Scanner s = new Scanner(System.in); // 從鍵盤接收資料
-
// next方式接收字串
-
System.out.println("next方式接收:");
-
// 判斷是否還有輸入
-
if (s.hasNext()) {
-
String str1 = s.next();
-
System.out.println("輸入的資料為:" + str1);
-
}
-
s.close();
-
}
-
}
-
next方式接收:
-
hello world
-
輸入的資料為:hello
由結果可知:
- 1、一定要讀取到有效字元後才可以結束輸入。
- 2、對輸入有效字元之前遇到的空白,next() 方法會自動將其去掉。
- 3、只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符。
- next() 不能得到帶有空格的字串。
nextLine()的使用方法演示:
-
import java.util.Scanner;
-
public class scannertest2 {
-
public static void main(String[] args) {
-
Scanner s = new Scanner(System.in); // 從鍵盤接收資料
-
// next方式接收字串
-
System.out.println("nextLine方式接收:");
-
// 判斷是否還有輸入
-
if (s.hasNextLine()) {
-
String str2 = s.nextLine();
-
System.out.println("輸入的資料為:" + str2);
-
}
-
s.close();
-
}
-
}
[plain] view plain copy
- <code class="language-java">nextLine方式接收:
- hello world 2018
- 輸入的資料為:hello world 2018</code>
由上面可以看出,nextLine()方法具有以下特點:
- 1、以Enter為結束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字元;
- 2、可以獲得空白,都會讀入,空格等均會被識別;
注意:如果要輸入 int 或 float 型別的資料,在 Scanner 類中也有支援,但是在輸入之前最好先使用 hasNextXxx() 方法進行驗證,再使用nextXxx() 來讀取,下面實現的功能是可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果:
-
import java.util.Scanner;
-
public class scandemo {
-
public static void main(String[] args) {
-
System.out.println("請輸入數字:");
-
Scanner scan = new Scanner(System.in);
-
double sum = 0;
-
int m = 0;
-
while (scan.hasNextDouble()) {
-
double x = scan.nextDouble();
-
m = m + 1;
-
sum = sum + x;
-
}
-
System.out.println(m + "個數的和為" + sum);
-
System.out.println(m + "個數的平均值是" + (sum / m));
-
scan.close();
-
}
-
}
-
請輸入數字:
-
20.0
-
30.0
-
40.0
-
end
-
3個數的和為90.0
-
3個數的平均值是30.0