user2908744
user2908744

Reputation: 15

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. 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. 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);
}

}

Upvotes: 1

Views: 1801

Answers (4)

binderbound
binderbound

Reputation: 799

You are adding a newline ("\n") to your input, (inputGrade.toUpperCase()+"\n";) so none of your cases are valid. That is, "A" does not equal "A\n"

I think you should not use "gradeEntered" and instead use:

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.

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. 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.

Upvotes: -1

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

Upvotes: 0

Eric Haynes
Eric Haynes

Reputation: 5786

The problem is that your switch statement is checking the value of grade, but your input is stored in 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. 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).

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. 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. The second time, it checks the first string. When you hit 'q', it breaks, and skips your last input. 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. The points per score should take the weight of credits as a positive, not a negative. Something like: 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.

Upvotes: 1

binderbound
binderbound

Reputation: 799

Your switch statement is using grade which seems to be never written to. It's always "". You get inputGrade, but you don't write to grade itself.

As it is always "", you always get nothing from your switch

Upvotes: 1

Related Questions