我有一个我做过的平均程序,我试图只允许它接受数字。其他一切都有效,但我似乎无法弄明白。我还在学习,任何建议或指针都会很棒!
这是我的代码。
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)
在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);