我需要能够在while循环中按'q'才能让它退出循环。然后,我需要代码才能显示其旁边的等级的学分。接下来,我必须根据他们的小时数和成绩输入显示他们的GPA。每次按'q'退出时,程序停止并且不显示任何内容。请帮忙!
package shippingCalc;
import javax.swing.JOptionPane;
public class Gpa {
public static void main(String[] args) {
String input = "";
String let_grade;
int credits = 0;
double letterGrade = 0;
int course = 1;
String greeting = "This program will calculate your GPA.";
JOptionPane.showMessageDialog(null, greeting,"GPA Calculator",1);
while(!input.toUpperCase().equals("Q"))
{
input = JOptionPane.showInputDialog(null, "Please enter the credits for class " + course );
credits = Integer.parseInt(input);
course ++;
input = JOptionPane.showInputDialog(null,"Please enter your grade for your " +credits + " credit hour class");
let_grade = input.toUpperCase();
char grade = let_grade.charAt(0);
letterGrade = 0;
switch (grade){
case 'A': letterGrade = 4.00;
break;
case 'B': letterGrade = 3.00;
break;
case 'C': letterGrade = 2.00;
break;
case 'D': letterGrade = 1.00;
break;
case 'F': letterGrade = 0.00;
break;
}
}
JOptionPane.showMessageDialog(null, course++ + "\n\n It Works" + letterGrade);
}
}
答案 0 :(得分:0)
我认为问题是,在第二次弹出窗口之后,信用是一个int
input = JOptionPane.showInputDialog(null,
"Please enter the credits for class " + course);
您可以将任何用户类型分配给int信用,因此如果您输入字符串q或Q,它将会中断。另外,请记住,while循环条件仅在迭代开始时每次迭代检查一次,因此在此之前它不会知道输入的值
有几种方法可以解决这个问题。一种快速简便的方法是在将用户输入分配给信用
之前插入这行代码 if(input.equalsIgnoreCase("q")){
continue;//will allow input to be checked immediately before assigning to credits
}