在筆試編程過程中,關(guān)于數(shù)據(jù)的讀取如果迷迷糊糊,那后來的編程即使想法很對,實現(xiàn)很好,也是徒勞,于是在這里認(rèn)真總結(jié)了java scanner 類的使用
通過 scanner 類來獲取用戶的輸入,下面是創(chuàng)建 scanner 對象的基本語法:
1
|
scanner s = new scanner(system.in); // 從鍵盤接收數(shù)據(jù) |
接下來我們演示一個最簡單的數(shù)據(jù)輸入,并通過 scanner 類的 next() 與 nextline() 方法獲取輸入的字符串,在讀取前我們一般需要 使用 hasnext 與 hasnextline 判斷是否還有輸入的數(shù)據(jù):
next() 與 nextline() 區(qū)別
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); // 從鍵盤接收數(shù)據(jù) // next方式接收字符串 system.out.println( "next方式接收:" ); // 判斷是否還有輸入 if (s.hasnext()) { string str1 = s.next(); system.out.println( "輸入的數(shù)據(jù)為:" + str1); } s.close(); } } |
next方式接收:
hello world
輸入的數(shù)據(jù)為:hello
由結(jié)果可知:
1、一定要讀取到有效字符后才可以結(jié)束輸入。
2、對輸入有效字符之前遇到的空白,next() 方法會自動將其去掉。
3、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結(jié)束符。
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); // 從鍵盤接收數(shù)據(jù) // next方式接收字符串 system.out.println( "nextline方式接收:" ); // 判斷是否還有輸入 if (s.hasnextline()) { string str2 = s.nextline(); system.out.println( "輸入的數(shù)據(jù)為:" + str2); } s.close(); } } |
nextline方式接收:
hello world 2018
輸入的數(shù)據(jù)為:hello world 2018
由上面可以看出,nextline()方法具有以下特點(diǎn):
1、以enter為結(jié)束符,也就是說 nextline()方法返回的是輸入回車之前的所有字符;
2、可以獲得空白,都會讀入,空格等均會被識別;
注意:如果要輸入 int 或 float 類型的數(shù)據(jù),在 scanner 類中也有支持,但是在輸入之前最好先使用 hasnextxxx() 方法進(jìn)行驗證,再使用 nextxxx() 來讀取,下面實現(xiàn)的功能是可以輸入多個數(shù)字,并求其總和與平均數(shù),每輸入一個數(shù)字用回車確認(rèn),通過輸入非數(shù)字來結(jié)束輸入并輸出執(zhí)行結(jié)果
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( "請輸入數(shù)字:" ); 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 + "個數(shù)的和為" + sum); system.out.println(m + "個數(shù)的平均值是" + (sum / m)); scan.close(); } } |
請輸入數(shù)字:
20.0
30.0
40.0
end
3個數(shù)的和為90.0
3個數(shù)的平均值是30.0
總結(jié)
以上所述是小編給大家介紹的java scanner 類的使用小結(jié),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://blog.csdn.net/sinat_41815248/article/details/83104824