开发者

How can I use a switch() statement to convert from a numeric to a letter grade?

This IS NOT homework, but it is a practice that the teacher gave us to help study for a test. But i will not be turning this in to the teacher. (i'm hoping that is allowed)

He wants a user to input a grade and have it assigned a letter grade. It would be easy with if statements, but i can't use ANY! I have to use the switch method.

Here is my functional class:

public class Grade {

public double getGrade(int开发者_开发知识库 input)
 {
  double inputGrade;
  switch(input)
  {
   case 1: inputGrade >= 90;
       break;
   case 2: inputGrade >= 80;
       break;
   case 3: inputGrade >= 70;
       break;
   default:
       grade = 60;
  }
  return grade;

 }

}

Here is my test class:

import java.util.*;
public class TestGrade
{
 public static void main(String[] args)
 {
  Scanner scan = new Scanner(System.in);
  int input = scan.nextInt();
  Grade lGrade = new Grade();
  double finalGrade = lGrade.getGradeSwitch(input);
  System.out.println("Your toll is $" + finalGrade);
 }

}

I just haven't been programming enough to have this analytical mind. I HAVE tried to complete it, i just haven't found a way to covert the user input (int) into a letter grade (string) without if statements.

I know this is incomplete, but this is as far as I could go without making errors.

EDIT:WOW! Thanks guys, i hate to pick a single correct answer, because a lot of you helped me!

This is what i ended up with (that worked :D)

public String getGrade(int input)
{
    String letterGrade;
    switch(input/10)
    {
        case 9: letterGrade = "A";
                  break;
        case 8: letterGrade = "B";
                  break;
        case 7: letterGrade = "C";
                  break;
        case 6: letterGrade = "D";
        default:
                  letterGrade = "F";
    }
    return letterGrade;

}


OK, my assumption is that you will enter a numeric grade 0-100, and that the letter grades you want go as "90-100: A; 80-89: B; ...; 60-69: D; 0-59: F".

If that is not the case, your first lesson to be learned about programming is: the most important part of coding is clearly writing out specifications and requirements

Having said that, there are smart and dumb approaches.

  • Dumb approach:

    • Use a switch on the "input" as you do now

    • Since values 90, 91... 100 are all supposed to be treated the same, put them all in as separate switch cases but only do the work in the last one (known as fall-through; see SwitchDemo2 on this page for how that works)

    • For the last value (say, 90 if you start from 100 and go down), the switch statement would be letterGrade = "A"; break;

    • once you reach case of 89, you repeat the same logic as you did for 100 through 90

    • Lather, Rinse, Repeat, till 60

    • Handle Fs as a default case.

This will be very long, quite dumb (as in, brute force) and very annoying to write, and a brilliant teaching tool for why you never want to write dumb code again if you can help it.

  • More elegant solution (insert appropriate Star Wars quote here)

    • What do you see in common between every # that correspons to "A"?

    Right, it's the fact that, aside from 100, they all are 2-diit #s starting with 9.

    So, to handle them all in 1 case statement, wouldn't it be wonderful to switch on some value that gives you "9" for all #s between 90 and 99?

    I hope you know the answer right away... hint below...

    Yes, just divide whole by 10!

    So, you need to have a switch on your numeric grade diveded by 10, with cases of 10, 9, 8, 7, 6 and default mapping to F.

Hope this covers enough ground for you to come up with working solution, while showing how the analysis might work as well.


I commented this as thoroughly as I could. Hopefully you will be able to follow along. As this is not a homework question, I have no problem posting a solution. Sometimes you just need to see the code to "get it", so here it is. If you have any questions about what I've written, leave a comment and I'll clarify the answer.

public static String getGrade(int numberGrade) {
    // There are two parts of the number grade that you really 
    // care about. The first is the quotient after division 
    // by 10. The second is the remainder after division by 
    // 10. The quotient will tell you where it is an A, B, C
    // D, or F. The remainder will tell you whether it should 
    // have a +, -, or nothing following the letter.
    // 
    // Let's take the grade 73 as an example. The quotient would 
    // be 7, with a remainder of 3. Because it has a quotient of 
    // 7, you know it's a C. Because of the 3, you know it should 
    // have a minus sign (-) after it.
    //
    // Once you know the pattern, you can pretty easily apply 
    // a switch statement to it and produce a letter grade.

    // Variables for the quotient and remainder, described above
    int quotient = numberGrade / 10;
    int remainder = numberGrade % 10;

    // This will hold the final letter grade
    String letterGrade;

    switch (quotient) {
        case 10:
            // The student got a 100%, so just return A+
            return "A+";
        case 9:
            // 90-99 is an A
            letterGrade = "A"; break;
        case 8:
            // 80-89 is a B
            letterGrade = "B"; break;
        case 7:
            // 70-79 is a C
            letterGrade = "C"; break;
        case 6:
            // 60-69 is a D
            letterGrade = "D"; break;
        default:
            // Anything 59 or below is an F
            return "F";
    }

    switch (remainder) {
        // For example, 70-73 are C-
        case 0: case 1: case 2: case 3:
            letterGrade += "-"; break;
        // Likewise, 77-79 are C+
        case 7: case 8: case 9:
            letterGrade += "+"; break;
        // Everything else just falls through, no + or - needed
    }

    // You are left with a letter grade consisting of 
    // an A, B, C, D or F, and a plus or minus where 
    // it is appropriate.
    return letterGrade;
}

And here is a really simple demonstration of this method:

for (int i = 100; i >= 0; i--) {
    System.out.println(i + " = " + getGrade(i));
}

It will print the following:

100 = A+
 99 = A+
 98 = A+
 97 = A+
 96 = A
 95 = A
 94 = A
 93 = A-
 92 = A-
 91 = A-
 90 = A-
 89 = B+
 88 = B+
 87 = B+
 86 = B


The switch statement does not take conditional values, ie it doesnt look for a true or false answer like inputGrade >= 70;, instead it looks for whether the item n in switch(n) is equal to x of the casex:.

Also, switch cases end with colons (:), not semis.

See this link for a generic explanation of the switch statement with a specific Java example.


Here's another hint as to how to do this.

What would happen if you integer divided the grade by 10?


Switch statements only work with values matching the given cases (along with a default). The only way to write this using a switch statement is to have a case for every possible score.

You would do this like:

switch (score)
{
    case 0:
    case 1:
    ...
    case 80:
    case 81:         
    ...
    case 89:
      return "B";
    case 90:
    ...
    case 100:
      return "A";
      break;
}

OR

You can cut it down to a a list of 11 possible cases by dividing by 10 first.

That would leave you with:

switch (score / 10)
{
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
       return "F";
    case 5:
       return "E";
    case 6:
       return "D";
    case 7:
       return "C";
    case 8:
       return "B";
    case 9:
    case 10:
       return "A";
}

Or something similar (of course this assumes you have grades corresponding to 50+ = E, 90+ = A and so on).


Here's a starting point: The 'A' character, as an integer, has the value 65. What do you suppose happens if you convert the value 66 to a character?


make this correction

  double grade; // i think you mispelled it inputGrade

and

   case 1: grade = 90; // inputGrade >= 90 is an expression and is not valid
       break;


Have you covered Enums yet? My suggestion would be to think about how an enumeration might help you get at your answer. Sorry, I can't give you any more help than that without ruining your aha moment.


I don't see anywhere in your code where you will return back a letter.

You may want to write it out in English, somewhat, and see what you are missing.

For example: User inputs numeric grade Numeric grade is converted into a letter grade Print out numeric and letter grade.

Then, write out the main tough part, part 2. Possible grades are ... Possible input ranges are ... Return letter grade

If you write it our more clearly, very step-by-step, as that is how the computer will process it, then you should see how to do it.

Pretend you are explaining to a second-grader how to do this, it has to be very basic instructions.


First off, if your function is to take a grade as an integer and return a letter grade, why does it have a return type of double?

After dealing with that, here is a hint:

The grade could range from 0 to 100, so that is 101 cases to handle in your switch statement. So you could write out all 101 cases if you wanted. But, can you think of a way to reduce the number of cases? (big hint: all grade boundaries are a multiple of 10)


I was bored and came up with this. I know it doesn't use switch statements either, but anywho:

    private string GetGrade(int grade)
    {
        return ((char)((int)(Math.Max((Math.Min(10 - (grade / 10) + 64, 69)), 65))))
               .ToString().Replace("E", "F");
    }

I just wanted to see if I could do it using character codes. There's probably an even shorter way, but oh well :) Oh, and sorry, it's C#.


How about this:

static int[]     SCORES =
    { 90, 80, 70, 60, 0 };  

static String[]  GRADES =
    { "A", "B", "C", "D", "F" };  

String letterGrade(int pct)
{
    for (int i = 0;  i < SCORES.length;  i++)
        if (pct >= SCORES[i])
            return GRADES[i];
}

This assumes that pct is positive. It uses a single if statement, so I'm not sure if this qualifies as a valid solution or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜