這個(gè)類可以用來(lái)獲取用戶的輸入,先給個(gè)基本的語(yǔ)法;
Scanner s = new Scanner(System.in);
下面隊(duì)一個(gè)數(shù)據(jù)的輸入,通過(guò)Scanner類的next()和nextLine()方法來(lái)獲取輸入的東西,讀取時(shí)一般都需要用hanNext和hasNextLine來(lái)盤對(duì)一下是否又輸入的東西。
next方法:
public static void main(String [] args){
Scanner s = new Scanner(System.in); //從鍵盤接受數(shù)據(jù)
System.out.println("next方式接受:");//next方法接受字符串
if(scan.hasNext(){ ? ? ? ? //判斷有沒(méi)有輸入
String str = scan.next();
System.out.println("輸入的數(shù)據(jù)是:"+str);
}
}
nextLine方法:
public static void main (String [] arge){
Scanner scan = new Scanner(System.in);
System.out.println("nextLine方法接收:" );
if(scan.hasNextLine()){
?String s = scan.nextLine();
System.out,println("輸入的東西是:"+s);
}
}
next() 與 nextLine() 區(qū)別
next():
1、一定要讀取到有效字符后才可以結(jié)束輸入。
2、對(duì)輸入有效字符之前遇到的空白,next() 方法會(huì)自動(dòng)將其去掉。
3、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結(jié)束符。
next() 不能得到帶有空格的字符串。
nextLine():
1、以Enter為結(jié)束符,也就是說(shuō) nextLine()方法返回的是輸入回車之前的所有字符。
2、可以獲得空白。
下面來(lái)偷學(xué)一個(gè)求平均數(shù)的簡(jiǎn)單方法(比自己以前用的要簡(jiǎn)便):
public static void main(String[] args){
?Scanner scan = new Scanner(System.in);
?double sum = 0;
?int m=0;
?while(Scan.hasNextDouble()){
? double x = scan.nextDouble();
? m+=1;
? sum+=x;
}
? ?System.out.println(m+"個(gè)數(shù)的和為:"+sum);
? System.out.println(m+"個(gè)書的平均數(shù)是"+(sum/m));
}