0

我需要能够在 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);
    }
}
4

1 回答 1

0

我认为的问题是 credits 是一个 int 并且在第二个弹出窗口之后

input = JOptionPane.showInputDialog(null, 
"Please enter the credits for class " + course);

您将用户键入的任何内容分配给 int 信用,因此如果您输入 String q 或 Q 它会中断。另外,请记住,while 循环条件在每次迭代时仅在迭代开始时检查一次,因此直到那时它才知道输入的值

有几种方法可以解决这个问题。一种快速简便的方法是在将用户输入分配给信用之前插入这行代码

 if(input.equalsIgnoreCase("q")){
    continue;//will allow input to be checked immediately before assigning to credits
}
于 2013-10-22T18:22:05.200 回答