多种情况 - 基于值范围而不是 Java 中的单个值进行测试?
作为学习编写 Java 的一部分,我在网上发现了 switch
语句用于多种情况。
对我来说,这个语句的问题在于,它将参数与我用作 case 的单个数字进行比较,但是如果我想根据参数所属的值范围来区分流,该怎么办?
有没有比使用大量 if 更优雅的方法?我正在寻找类似 cond 的内容
方案中的
语句。
public class Assignment02Q03 {
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
if (grade >= 90) {
System.out.println("A");
} else {
if (grade >= 80 ){
System.out.println("B");
} else {
if (grade >= 70){
System.out.println("C");
}else {
if (grade >= 60){
System.out.println("D");
}else {
System.out.println("F");
}
}
}
}
}
}
一定有更优雅的东西:)
谢谢!
As part of learning to write Java I found on the web the switch
statement for multiple cases.
The problem for me with this statement is that it compares the argument to the single numbers that I use as case
s, but what if I want to differentiate the flow based on the range of values the argument belongs to?
Is there a more elegant way than using a lot of if
s? I am looking for something like the cond
statement in Scheme.
public class Assignment02Q03 {
public static void main(String[] args){
int grade = Integer.parseInt(args[0]);
if (grade >= 90) {
System.out.println("A");
} else {
if (grade >= 80 ){
System.out.println("B");
} else {
if (grade >= 70){
System.out.println("C");
}else {
if (grade >= 60){
System.out.println("D");
}else {
System.out.println("F");
}
}
}
}
}
}
There must be something more elegant :)
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一般写为:
并不是说
else if
有什么特别的。大括号可以用单个语句替换,在此为if
-else
语句。缩进与该语言中的其他内容不同,但它是一个应该很容易理解的习惯用法。对于表达式,还有三元运算符:
Generally written as:
Not that there is anything special about
else if
. The braces can be replaced by a single statement, in this anif
-else
statement. The indentation is like nothing else in the language, but it's an idiom that should be easy to follow.For an expression, there is also the ternary operator:
在
Java
中有ifs
、switch case
结构和三元运算符
(这是一个缩短的if )。我想没什么优雅的:)
In
Java
there are theifs
,switch case
construct andternary operator
(which is a shortenedif
). Nothing elegant I guess:)该语言中没有内置任何内容。对于简洁快速的代码,您可以创建一个映射,将测试值映射到
Runnable
或Callable
操作。但是,这往往有点不透明,因为您必须在代码中的其他位置查找有关地图内容的信息。There's nothing built into the language. For terse and quick code, you can create a Map that maps your test values to
Runnable
orCallable
actions. However, that tends to be a little opaque because you have to look elsewhere in your code for info on what's in the map.与许多其他语言一样,您可以使用三元 if 测试。
Like many other languages you may use a ternary if-test.
Java中有OOP和多态性)
你可以这样写smt,
它看起来比较冗长,但它在实际任务中有效。 Java 不适合优雅的解决方案。 Java 用于工作。感受Java)
There is OOP and polymorphism in Java)
You can write smt like
It seems more verbose, but it works in real tasks. Java isn't for elegant solutions. Java for work. Feel Java)
可以这样写......
can be written like this....