java 如何在条件 (if/then) 语句中包含范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14615802/
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
How can I include range in a conditional (if/then) statement?
提问by user2027323
I'm trying to write a program in Java that returns a letter grade when the grades for all quarters, as well as the grades for the midterms and finals are in. So far this is what it looks like:
我正在尝试用 Java 编写一个程序,当所有季度的成绩以及期中和期末成绩都在时,它会返回一个字母成绩。到目前为止,它是这样的:
public static void main (String args[])
{
System.out.println("To figure out final grade answer these questions. Use only numbers, and include decimal points where applicable");
Scanner g = new Scanner(System.in);
System.out.println("What was your quarter one grade?");
int o = g.nextInt();
System.out.println("What was your quarter two grade?");
int t = g.nextInt();
System.out.println("What was your quarter three grade?");
int h = g.nextInt();
System.out.println("What was your quarter four grade?");
int r = g.nextInt();
System.out.println("What was your grade on the midterm?");
int m = g.nextInt();
System.out.println("What was your grade on the final?");
int f = g.nextInt();
double c = 0.2 * o + 0.2 * t + 0.2 * h + 0.2 * r + 0.1 * m + 0.1 *f;
if(c >= 95)
{
System.out.println("A+");
}
else if(c = ?)
{
System.out.println("A");
}
}
}
}
I want to show a range of 90 to 94 in the last else if statement in the code. I was recommended I use Math.random as a command, but I don't know what equation to write so that it works within the range I mentioned. Any help would be much appreciated. Thanks in advance.
我想在代码的最后一个 else if 语句中显示 90 到 94 的范围。有人建议我使用 Math.random 作为命令,但我不知道要写什么方程才能在我提到的范围内工作。任何帮助将非常感激。提前致谢。
回答by nneonneo
Since you are already testing c >= 95
in the first statement, you need only check the lower bound:
由于您已经c >= 95
在第一条语句中进行了测试,因此您只需要检查下限:
if(c >= 95) { /* A+ */ }
else if(c >= 90) { /* A */ }
else if(c >= 85) { /* A- */ }
...
回答by Matt9Atkins
if(c >= 95)
{
System.out.println("A+");
}
else if(c >= 90 && c <=94)
{
System.out.println("A");
}
EDIT you can get rid of && c <=94
if you want as you have already checked the upper bound
编辑你可以摆脱, && c <=94
如果你想,因为你已经检查了上限
回答by Hamzeen Hameem
Here's a slightly different approach to generate the grades dynamically,
这是一种稍微不同的动态生成成绩的方法,
private static final String[] constants = {"F","D","C","B","A"};
public String getGrade(float score) {
if(score < 0)
throw new IllegalArgumentException(Float.toString(score));
if((int)score <= 59)
return constants[0];
if((int)score >= 100)
return constants[4];
int res = (int) (score/10.0);
return constants[res-5];
}