2015-09-04 92 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); 
相关问题