我想根据成绩的分数打印一些文字:
0
(不包括)和100
:它打印Your Grade Is : <message>
。因此<message>
是依赖于的得分子范围。100
或等于或等于0
:我想打印Enter Valid Number
注意: 我不想重复Your Grade Is
代码中的文本:D
double score = 16;
String grade = (score <= 100 && score >= 85) ? "Excellent"
: (score >= 75 && score < 85) ? "Very Good"
: (score >= 65 && score < 75) ? "Good"
: (score >= 50 && score < 65) ? "pass"
: (score > 0 && score < 50) ? "Fail" : "Enter Valid Number !";
System.out.println(">>>"+grade);
发布于 2019-03-15 13:47:17
if
如果您的条件数量很少,则应使用if
语句。它们使您的代码可读。还可以通过更改某些行来轻松修改某些条件/逻辑(因为它们不像三元运算符那样链接)。
我建议只使用三元表达式(result = (value != null) ? value : default
),只要你可以将它放在一行中,并且可读性不受影响(例如,为了分配默认值)。
public static String buildMessageForScore(double score) {
if (score > 0 && score <= 100) {
String message = "Your Grade Is: ";
if (score < 50) return message + "Failed";
if (score < 65) return message + "Passed";
if (score < 75) return message + "Good";
if (score < 85) return message + "Very Good";
if (score <= 100) return message + "Excellent";
}
return "Enter Valid Number!";
}
IllegalArgumentException
如果参数分数无效,您也可以抛出一个。if
验证得分是否在范围内。return
显示相关消息并离开方法(短路)。因为return
在每个条件之后直接你可以省略通常的if .. else
样式(与break
in 相同switch .. case
)。由于每个条件都在一行中,因此它的可读性更高(哪个分数限制属于哪个消息)。发布于 2019-03-15 15:14:19
试试这个:
String grade = score > 100 || score < 0 ? "Enter Valid Number !" :
"Your Grade Is" + ((score <= 100 && score >= 85) ? "Excellent"
: (score >= 75 && score < 85) ? "Very Good"
: (score >= 65 && score < 75) ? "Good"
: (score >= 50 && score < 65) ? "pass"
: (score > 0 && score < 50) ? "Fail");
System.out.println(">>>"+grade);
https://stackoverflow.com/questions/-100006457
复制相似问题