我正在编写一个简单的程序并且它已经在工作我已经限制用户输入负数和超过100个数字,我现在需要做的是限制用户输入字符串或字符或符号,一切都不是一个数字,但我根本不知道有人可以帮助我:)。
import java.util.Scanner;
public class Average {
public static void main(String[]args) {
double Math;
double Science;
double Filipino;
double English;
double sum;
double average;
Scanner input = new Scanner(System.in);
do{
System.out.println("Please enter your grade in Math");
Math = input.nextDouble();
if(Math<0||Math>100){
System.out.println("You entered "+Math+", which is an invalid grade, please try again.");}
}
while(Math<0||Math>100);
do{
System.out.println("Please enter your grade in Science");
Science = input.nextDouble();
if(Science<0||Science>100){
System.out.println("You entered "+Science+", which is an invalid grade, please try again.");}
}
while(Science<0||Science>100);
do{
System.out.println("Please enter your grade in Filipino");
Filipino = input.nextDouble();
if(Filipino<0||Filipino>100){
System.out.println("You entered "+Filipino+", which is an invalid grade, please try again.");}
}
while(Filipino<0||Filipino>100);
do{
System.out.println("Please enter your grade in English");
English = input.nextDouble();
if(English<0||English>100){
System.out.println("You entered "+English+", which is an invalid grade, please try again.");}
}
while(English<0||English>100);
sum = Math + Science + Filipino + English;
average = sum / 4;
System.out.println("Your total average is: "+average);
if(average>=75){
System.out.println("Remarks: Passed");}
else{
System.out.println("Remarks: Failed");}
}
}
答案 0 :(得分:0)
将输入读数放在try块中并使用以下catch块。
catch (NumberFormatException ex) {
//handle exception here
}
答案 1 :(得分:0)
您可以使用java的内置检查NumberFormatException
。
String s = input.next();
double value = 0.0;
try{
value = Double.parseDouble(s);
//your code logic
} catch(NumberFormatException e){
System.out.println("Please Enter a number");
//your logic to take input again
}
答案 2 :(得分:0)
try{
do{
System.out.println("Please enter your grade in Math");
Math = input.nextDouble();
if(Math<0||Math>100){
System.out.println("You entered "+Math+", which is an invalid grade, please try again.");}
}
while(Math<0||Math>100);}
catch (NumberFormatException ex) {
}