简体   繁体   English

Java 嵌套 if to switch 语句

[英]Java nested if to switch statement

I'm having trouble transforming the following nested if statement below, into an equivalent switch statement.我无法将下面的嵌套 if 语句转换为等效的 switch 语句。 If anyone can give me some advice, it would be appreciated.如果有人能给我一些建议,将不胜感激。

if (num1 == 5)
    myChar = ‘A’;
else
if (num1 == 6 )
    myChar = ‘B’;
else
if (num1 = 7)
    myChar = ‘C’;
else
    myChar = ‘D’;

Pretty straightforward, just use the number as the thing you want to switch on.非常简单,只需使用数字作为您想要打开的东西。 Your else case becomes the default case.您的else情况成为default情况。

switch (num1) {
    case 5:
        myChar = 'A';
        break;
    case 6:
        myChar = 'B';
        break;
    case 7:
        myChar = 'C';
        break;
    default:
        myChar = 'D';
        break;
}

For more details chek the documentation : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html有关更多详细信息,请查看文档: https : //docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

switch(num1){
 case 5:
   myChar = ‘A’;
   break;
 case 6:
   myChar = ‘B’;
   break;
 case 7:
   myChar = ‘C’;
   break;
 default:
   myChar = ‘D’;
}

If the values follow a simple pattern like this, you don't need a switch at all.如果值遵循这样的简单模式,则根本不需要switch For example you can do例如你可以做

myChar = num1 >= 5 && num1 <= 7 ? (char) ('A' + num1 - 5) : 'D';

If num1 is always 5 , 6 , 7 or 8 you can just do如果num1总是5 , 6 , 78你可以这样做

myChar = (char) ('A' + num1 - 5);

In JDK 12, extended switch will allow you to assign a char value directly to the switch.在 JDK 12 中,扩展开关将允许您直接为开关分配一个字符值。 Construct your switch as such:构造您的开关,如下所示:

char myChar = switch(num1) {
    case 5 -> 'A';
    case 6 -> 'B'; 
    case 7 -> 'C';
    default -> 'D';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM