在筆試編程過程中,關于數據的讀取如果迷迷糊糊,那后來的編程即使想法很對,實現很好,也是徒勞,于是在這里認真總結了java scanner 類的使用
通過 scanner 類來獲取用戶的輸入,下面是創建 scanner 對象的基本語法:
1
|
scanner s = new scanner(system.in); // 從鍵盤接收數據 |
接下來我們演示一個最簡單的數據輸入,并通過 scanner 類的 next() 與 nextline() 方法獲取輸入的字符串,在讀取前我們一般需要 使用 hasnext 與 hasnextline 判斷是否還有輸入的數據:
next() 與 nextline() 區別
next()的使用方法演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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()的使用方法演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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(); } } |
nextline方式接收:
hello world 2018
輸入的數據為:hello world 2018
由上面可以看出,nextline()方法具有以下特點:
1、以enter為結束符,也就是說 nextline()方法返回的是輸入回車之前的所有字符;
2、可以獲得空白,都會讀入,空格等均會被識別;
注意:如果要輸入 int 或 float 類型的數據,在 scanner 類中也有支持,但是在輸入之前最好先使用 hasnextxxx() 方法進行驗證,再使用 nextxxx() 來讀取,下面實現的功能是可以輸入多個數字,并求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入并輸出執行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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
總結
以上所述是小編給大家介紹的java scanner 類的使用小結,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/sinat_41815248/article/details/83104824