Java 如何使用 switch() 语句将数字等级转换为字母等级?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1535076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:56:07  来源:igfitidea点击:

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

javaswitch-statement

提问by Phil

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.

他希望用户输入一个等级并为其分配一个字母等级。使用 if 语句会很容易,但我不能使用任何!我必须使用 switch 方法。

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.

我只是没有足够的编程来拥有这种分析思维。我试图完成它,我只是没有找到一种方法来将用户输入(int)转换为没有 if 语句的字母等级(字符串)。

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)

这就是我最终得到的(有效: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;

}

采纳答案by DVK

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

好的,我的假设是您将输入 0-100 的数字等级,并且您想要的字母等级为“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.

  • 愚蠢的做法:

    • 像现在一样使用“输入”上的开关

    • 由于值 90、91... 100 都应该被视为相同的,因此将它们全部放在单独的 switch case 中,但只在最后一个执行(称为 fall-through;请参阅本页上的 SwitchDemo2 了解如何作品

    • 对于最后一个值(例如,如果您从 100 开始向下走,则为 90),switch 语句将是 letterGrade = "A"; 休息;

    • 一旦达到 89 的情况,就重复与 100 到 90 相同的逻辑

    • 起泡,冲洗,重复,直到 60

    • 将 Fs 作为默认情况处理。

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.

  • 更优雅的解决方案(在此处插入适当的星球大战报价

    • 您在与“A”对应的每个 # 之间看到什么共同点?

    是的,事实上,除了 100,它们都是以 9 开​​头的 2-diit #s。

    因此,要在 1 个 case 语句中处理所有这些问题,打开某个值,为 90 到 99 之间的所有 #s 提供“9”不是很好吗?

    我希望你马上知道答案......下面的提示......

    是的,只需将整体除以 10!

    所以,你需要在你的数字等级上有一个开关,在 10、9、8、7、6 的情况下,默认映射到 F。

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

希望这涵盖了足够的基础,让您提出可行的解决方案,同时展示分析如何工作。

回答by Matt

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?

这是一个起点:作为整数的“A”字符的值为 65。如果将值 66 转换为字符,您认为会发生什么情况?

回答by akf

The switch statement does not take conditional values, ie it doesnt look for a trueor falseanswer like inputGrade >= 70;, instead it looks for whether the item nin switch(n)is equal to xof the casex:.

switch语句不带条件的值,即它不找一个truefalse回答喜欢inputGrade >= 70;,而是查找该项目是否n在等于的。 switch(n)xcasex:

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

此外,switch case 以冒号 ( :)结尾,而不是半数。

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

有关带有特定 Java 示例的 switch 语句的一般解释,请参阅此链接

回答by Andrew Keith

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;

回答by Josh

Have you covered Enumsyet? 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.

你已经介绍过枚举了吗?我的建议是考虑枚举如何帮助您获得答案。对不起,我不能给你更多的帮助而不破坏你的啊哈时刻。

回答by James Black

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

然后,写出主要困难的部分,第 2 部分。可能的等级是......可能的输入范围是......返回字母等级

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.

假设您正在向二年级学生解释如何执行此操作,它必须是非常基本的说明。

回答by Anthony Mills

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

这是有关如何执行此操作的另一个提示。

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

如果用整数除以 10 会发生什么?

回答by James

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?

首先,如果您的函数是将成绩作为整数并返回字母成绩,为什么它的返回类型为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)

等级的范围可以从 0 到 100,因此在 switch 语句中要处理 101 种情况。因此,如果您愿意,您可以写出所有 101 个案例。但是,你能想出一种方法来减少病例数吗?(重要提示:所有等级界限都是 10 的倍数)

回答by RodeoClown

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.

Switch 语句仅适用于与给定情况匹配的值(以及默认值)。使用 switch 语句编写它的唯一方法是为每个可能的分数都有一个案例。

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.

您可以先除以 10,将其缩减为 11 种可能情况的列表。

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

或类似的东西(当然,这假设您的成绩对应于 50+ = E、90+ = A 等)。

回答by David R Tribble

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 pctis positive. It uses a single ifstatement, so I'm not sure if this qualifies as a valid solution or not.

这假设pct是积极的。它使用单个if语句,因此我不确定这是否符合有效解决方案的条件。