這個類可以用來獲取用戶的輸入茉帅,先給個基本的語法碧注;
Scanner s = new Scanner(System.in);
下面隊一個數(shù)據(jù)的輸入捍歪,通過Scanner類的next()和nextLine()方法來獲取輸入的東西,讀取時一般都需要用hanNext和hasNextLine來盤對一下是否又輸入的東西烫幕。
next方法:
public static void main(String [] args){
Scanner s = new Scanner(System.in); //從鍵盤接受數(shù)據(jù)
System.out.println("next方式接受:");//next方法接受字符串
if(scan.hasNext(){ ? ? ? ? //判斷有沒有輸入
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、對輸入有效字符之前遇到的空白糕珊,next() 方法會自動將其去掉动分。
3、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結(jié)束符红选。
next() 不能得到帶有空格的字符串澜公。
nextLine():
1、以Enter為結(jié)束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字符喇肋。
2坟乾、可以獲得空白。
下面來偷學一個求平均數(shù)的簡單方法(比自己以前用的要簡便):
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+"個數(shù)的和為:"+sum);
? System.out.println(m+"個書的平均數(shù)是"+(sum/m));
}