2015-09-04 170 views
-4

我有一個平均的程序,我已經做了一些,我試圖只允許它取數字。其他的工作,但我似乎無法弄清楚。我仍然在學習,所以任何建議或指針都會很棒!只允許在java中從用戶輸入中獲取數字

這是我的代碼。

import java.util.Scanner; 

public class THISISATEST { 
    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 
     int sum = 0; 
     int count = 0; 
     int i = 1; 
     while (i <= 10) { 
      i++; 

      { 
       System.out.print("Enter the test score: "); 
       int tS = keyboard.nextInt(); 
       count++; 
       sum = (sum + tS); 
      } 
      System.out.println(sum); 
     } 

     System.out.println("The Average is = " + sum/count); 
    } 
} 
+0

我覺得這是一個問題,而? –

+0

正確我希望用戶只能輸入數字,如果他們沒有,那麼可能會提示他們再次輸入數字。 – cw911

回答

1

內部while循環使用下面的代碼:

System.out.print("Enter the test score: "); 
while (!keyboard.hasNextInt()) {//Will run till an integer input is found 
    System.out.println("Only number input is allowed!"); 
    System.out.print("Enter the test score: "); 
    keyboard.next(); 
} 
int tS = keyboard.nextInt(); 
//If input is a valid int value then the above while loop would not be executed 
//but it will be assigned to your variable 'int ts' 
count++; 

sum = (sum + tS);