我是编程新手&我试着做一个算法来找出用户为每个科目输入的分数。在程序开始时,用户输入每个主题的所有标记。之后,电脑会自动按以下顺序打印所有的主题 subject - mark - grade
.
我使用do while循环来避免用户输入超出范围的数字。另外,我想使用try-catch和do-while来避免从用户那里得到无效的变量类型。我把整个试接动作放到另一个边做边做的循环中。因此,它必须是循环的,直到用户在异常存在时输入一个整数值。但是当我输入了一个错误的变量类型 A
当程序运行时,计算机判定所有剩余的输入都是无效变量,没有用户的输入,并将所有这些“等级”的“标记”打印为零和空 >>Subject_4 - 0 - null
. 否则,如果我输入一个正确的变量,它应该这样打印 >>Subject_1 - 56 - C
. 我怎样才能解决这个问题?请帮帮我。
public class findResults {
int getMark;
int setMark;
String setGrade;
int arrayIndex;
String [] subjects = {"Subject_1","Subject_2","Subject_3","Subject_4"};
int [] marks = new int [subjects.length];
String[] grades = new String [subjects.length];
public findResults(){
Scanner scan = new Scanner (System.in);
System.out.println("Enter your marks for each subjects!");
for (int t = 0;t<subjects.length;t++){
arrayIndex = t;
int x = 0;
do{
try {
do{
System.out.print(subjects[t]+" - ");
getMark = scan.nextInt();
setMark = ((getMark <= 100 && getMark >= 0)? getMark : (x=x-1));
x = x+1;
}while(x!=1);
} catch (Exception e) {
System.out.println("Please input valid number ..!");
}
}while(x!=x);
}
for (int i = 0; i<subjects.length;i++)
System.out.println(subjects[i]+" - "+marks[i]+" - "+ grades[i]);
}
public void setResult(){
if (setMark >= 75){
setGrade = "A";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=65){
setGrade = "A";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=65){
setGrade = "B";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=55){
setGrade = "C";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=35){
setGrade = "S";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >0){
setGrade = "W";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}else{
setGrade = "F";
marks[arrayIndex]= setMark;
grades[arrayIndex]= "Fail";
}
}
}
1条答案
按热度按时间yc0p9oo01#
考虑以下几点。
下面是示例运行的输出。