1. 程式人生 > 實用技巧 >Java07-2_Java流程控制--Scanner進階

Java07-2_Java流程控制--Scanner進階

 1 package Day07;
 2 
 3 
 4 import java.util.Scanner;
 5 
 6 public class Java07_3 {
 7     public static void main(String[] args) {
 8         Scanner scanner = new Scanner(System.in);
 9         //從鍵盤接收資料
10         int i=0;
11         float f=0.0f;
12         System.out.println("請輸入整數:");
13 
14         //
如果……那麼 15 if (scanner.hasNextInt()){ 16 i=scanner.nextInt(); 17 System.out.println("整數資料:"+i); 18 } 19 else{ 20 System.out.println("這個資料不是整數資料!"); 21 } 22 if (scanner.hasNextFloat()){ 23 f=scanner.nextFloat();
24 System.out.println("小數資料:"+f); 25 } 26 else { 27 System.out.println("這個資料不是小數資料!"); 28 } 29 scanner.close(); 30 } 31 }

practice:

輸入多個數字,並求其總和與平均數,每一個數字用回車鍵確認,通過輸入非數字來結束輸入並輸出執行結果

 1 package Day07;
 2 
 3 import java.util.Scanner;
4 5 public class Java07_4 { 6 public static void main(String[] args) { 7 Scanner scanner = new Scanner(System.in); 8 // 9 double sum = 0; 10 //計算輸入了多少個數字 11 int m = 0; 12 System.out.println("請輸入資料:"); 13 while (scanner.hasNextDouble()) {//通過迴圈判斷是否還有數字的輸入,並對每次輸出進行統計 14 double x= scanner.nextDouble(); 15 m+=1;//m++ 16 sum = sum + x; 17 System.out.println("你輸出了第"+m+"個數據,其總和為:"+sum); 18 } 19 System.out.println(m+"個數據的個數和為:"+sum); 20 System.out.println(m+"個數據的平均數為:"+(sum/m)); 21 scanner.close(); 22 } 23 }