简体   繁体   English

如何在while循环中正确使用switch语句

[英]How to properly use a switch statement in while loop

I don't think my switch statement is doing anything with my code, I'm new to java so I'm not sure how to use a switch statement in a while loop . 我不认为我的switch语句对我的代码有任何作用,我是java新手,所以我不确定如何在while loop使用switch语句。 I'm trying to take each grade/credit entered so I can find the GPA , but I added a System.out.print for the grades and it says it's worth 0 no matter what gets entered. 我正在尝试获取输入的每个成绩/学分,以便可以找到GPA ,但是我为成绩添加了System.out.print ,它说无论输入什么内容都值0。 Please help! 请帮忙!

package exercises;

import java.text.DecimalFormat;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class GPA_Calculator {

public static void main(String[] args)
{
    String greeting = "Hello, this program will calculate your GPA. You will be asked \n"+
            "to enter your letter grade for each class, then you will be asked to enter \n"+
            "the corresponding number of credits for that class. Once all the grades and credits\n"+
            "have been entered, the program will display your GPA.";
    JOptionPane.showMessageDialog(null,greeting,"Greeting - Introduction",1);

    char gradeEntered;
    String grade = "";
    String creditEntered = "";
    String inputGrade = "";
    String inputCredit = "";
    String enterGradePrompt = "Enter your letter grade (A, B, C, D, F)\n"+
            "Enter Q to display your results\n\n";
    String enterCreditPrompt = "Enter the credit hours for your course (0, 1, 2, 3, 4, 5, 6)\n"+
            "Enter Q to display your results\n\n";

    int points = 0, sum = 0, credits = 0, gradeCount = 0;

    while(!inputGrade.toUpperCase().equals("Q"))
    {
        inputGrade = JOptionPane.showInputDialog(null,enterGradePrompt,"Enter grade",1);
        gradeEntered = inputGrade.charAt(0);
        grade += inputGrade.toUpperCase()+"\n";

        inputCredit = JOptionPane.showInputDialog(null,enterCreditPrompt,"Enter grade",1);
        creditEntered += inputCredit+"\n";
        if(inputCredit.toUpperCase().equals("Q"))
            continue;
            credits = Integer.parseInt(inputCredit);
            credits++;

        switch (gradeEntered){
            case 'A':  points = 4;
                break;
            case 'B':  points = 3;
                break;
            case 'C':  points = 2;
                break;
            case 'D':  points = 1;
                break;
            case 'F':  points = 0;
                break;
            }
        sum += gradeEntered;
        gradeCount++;
    }

    // Prevents "Q" from being printed in results
    grade = grade.substring(0,grade.length()-2);
    creditEntered = creditEntered.substring(0,creditEntered.length()-2);

    DecimalFormat df = new DecimalFormat("#.##");
    double gpa = sum / gradeCount;

    String results = "The courses you entered are:\n\n"+
            "Grade  "+"Hours    \n"+
            grade+" "+creditEntered+"\n"+
            "Resulting in a GPA of "+df.format(gpa)+"\n\n"+
            "This program will now terminate!";

    JOptionPane.showMessageDialog(null, new JTextArea(results),
            "results from the Invitation list generator",1);
}

} }

The problem is that your switch statement is checking the value of grade , but your input is stored in inputGrade . 问题是您的switch语句正在检查grade的值,但是您的输入存储在inputGrade The former is never reassigned from the empty string, so points never gets incremented. 前者永远不会从空字符串中重新分配,因此点永远不会增加。

EDIT: To expand on the comment below: 编辑:扩展下面的评论:

  • the conditional in either a while or do/while loop isn't being checked. 不检查while循环或do / while循环中的条件。 You're checking it inside the loop and breaking out, which is fine, as you can just make an infinite loop and let the break terminate it. 您可以在循环中检查它并进行中断,这很好,因为您可以进行无限循环并让中断终止它。 However, it shouldn't be duplicated in the loop conditional. 但是,不应在循环条件中重复它。
  • You should do check that condition early. 您应该尽早检查该状况。 There's no sense in performing anything inside the loop if the user enters 'q' (also, then, you don't have to have the part where you try to strip it afterwards). 如果用户输入“ q”,则在循环内执行任何操作都是没有意义的(此外,您也不必在随后尝试剥离的部分上放置该部分)。

Also, you should always try to keep your variables as locally as possible. 另外,您应始终尝试将变量尽可能地保持在本地。 There's no need to have anything but the aggregators (totalXxx and yyyEntered in this case) outside of the loop. 除了循环外的聚合器(在这种情况下为totalXxx和yyyEntered),不需要任何其他东西。 It just makes it confusing for you in this case, as it's masking the source of your problem. 在这种情况下,这只会使您感到困惑,因为它掩盖了问题的根源。 When the switch statement hits the first time, it checks the empty string. switch语句首次命中时,它将检查空字符串。 The second time, it checks the first string. 第二次,它检查第一个字符串。 When you hit 'q', it breaks, and skips your last input. 当您按“ q”时,它将中断并跳过您的最后输入。 If these input variables were declared inside the loop, that would be immediately apparent. 如果在循环内声明了这些输入变量,那将立即显而易见。

Finally, while I'm here, you have an error in your gpa calculation. 最后,当我在这里时,您的gpa计算中存在错误。 The points per score should take the weight of credits as a positive, not a negative. 每分的分数应将学分的权重视为正数,而不是负数。 Something like: sum(grade * credits) / sum(credits) 诸如: sum(grade * credits) / sum(credits)

I can post fixed code if you want, but since I suspect this is an academic exercise, it would be more beneficial if you came to the solution yourself. 如果您愿意,我可以发布固定代码,但是由于我怀疑这是一项学术练习,因此如果您自己来解决方案,那将更加有益。

Your switch statement is using grade which seems to be never written to. 您的switch语句使用的grade似乎从未写入。 It's always "" . 总是"" You get inputGrade , but you don't write to grade itself. 您将获得inputGrade ,但不会编写grade本身。

As it is always "", you always get nothing from your switch 由于它始终是“”,因此您始终无法从开关中获得任何信息

You are appending each grade to your gradeEntered 您正在将每个年级附加到您的年级上

gradeEntered += inputGrade.toUpperCase()+"\n"; // at a point this is something like A\nB\nC\nD\nE.... so it will not match anyway
switch (gradeEntered) {
    case "A":  points = 4;
        break;
    case "B":  points = 3;
        break;
    case "C":  points = 2;
        break;
    case "D":  points = 1;
        break;
    case "F":  points = 0;
        break;
    }

so most of the times it will not match to any of your cases. 因此在大多数情况下,它都不适合您的任何情况。

Either you have to have a separate char for grade and use it in the switch or first use switch and then append it to your variable 您必须为等级分配一个单独的字符,然后在开关中使用它,或者先使用开关,然后将其附加到变量中

You are adding a newline ("\\n") to your input, ( inputGrade.toUpperCase()+"\\n"; ) so none of your cases are valid. 您正在向输入中添加换行符(“ \\ n”)( inputGrade.toUpperCase()+"\\n"; ),因此所有情况都不成立。 That is, "A" does not equal "A\\n" 也就是说,“ A”不等于“ A \\ n”

I think you should not use "gradeEntered" and instead use: 我认为您不应使用“ gradeEntered”,而应使用:

switch (inputGrade.toUpperCase())

especially since after running the loop more than once, your "gradeEntered" string will start to look like this: "A\\nB\\nF\\nQ\\n", which is very far removed from all your cases. 尤其是因为多次运行循环后,您的“ gradeEntered”字符串将开始看起来像这样:“ A \\ nB \\ nF \\ nQ \\ n”,该字符串与您的所有情况都相去甚远。

Also, switching on strings is not good practice - it is a newish development in java, and won't be supported by computers running older versions fo java - though for your own use, if the compiler doesn't complain then it is fine. 另外,打开字符串也不是一个好习惯-这是Java的新开发,并且运行Java的较早版本的计算机将不支持-尽管您可以自己使用,但如果编译器没有抱怨,那就很好。 Still, better to get in the habit of switching on chars or ints, since most other programming languages won't let you switch on strings. 尽管如此,还是要养成打开char或int的习惯,因为大多数其他编程语言都不允许您打开字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM