流程控制Day01—使用者互動Scanner
阿新 • • 發佈:2021-08-17
流程控制Day01—使用者互動Scanner
Scanner
//hasNext() //建立一個掃描器物件,用於接收鍵盤資料 Scanner scanner = new Scanner(System.in); System.out.println("使用next方式接收:"); //判斷使用者有沒有輸入字串 if (scanner.hasNext()) { //使用next方式接收 String str = scanner.next(); System.out.println("輸入的內容為:" + str); } //凡是屬於IO流的類如果不關閉會一直佔用資源,要養成好習慣用完就關掉 scanner.close(); //輸入hello world //輸出hello
//hasNextLine() //建立一個掃描器物件,用於接收鍵盤資料 Scanner scanner = new Scanner(System.in); System.out.println("使用next方式接收:"); //判斷是否還有輸入 if (scanner.hasNextLine()) { //使用next方式接收 String str = scanner.nextLine(); System.out.println("輸入的內容為:" + str); } scanner.close(); //輸入hello world //輸出hello world
//不使用if語句
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入資料:");
String str = scanner.nextLine();
System.out.println("輸入的內容為:" + str);
scanner.close();
通過Scanner類的next()與nextLine()方法獲取輸入的字串,在讀取前我們一般需要使用hasNext()與hasNextLine()判斷是否還有輸入的資料
next()
-
一定要讀取到有效字元後才可以結束輸入
-
對輸入有效字元之前遇到的空白,next()方法會自動將其去掉
-
只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符
-
☆next()不能得到帶有空格的字串☆
nextLine()
- 以Enter為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字元
- 可以獲得空白
例題:輸入多個數字,求總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果
Scanner scanner = new Scanner(System.in);
//和
double sum = 0;
//計算輸入了多少個數字
int m = 0;
//通過迴圈判斷是否還有輸入,並在裡面對每一次進行求和和統計
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
m = m + 1;
sum = sum + x;
System.out.println("你輸入了第"+m+"個數據");
}
System.out.println(m + "個數的和為" + sum);
System.out.println(m + "個數的平均值為" + (sum / m));
scanner.close();