Flapjack
Flapjack

Reputation: 31

Java nested if to switch statement

I'm having trouble transforming the following nested if statement below, into an equivalent switch statement. 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’;

Upvotes: 2

Views: 2509

Answers (4)

Tyrone Annor
Tyrone Annor

Reputation: 3

In JDK 12, extended switch will allow you to assign a char value directly to the switch. Construct your switch as such:

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

Upvotes: 0

Tahar Bakir
Tahar Bakir

Reputation: 716

For more details chek the documentation : 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’;
}

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37655

If the values follow a simple pattern like this, you don't need a switch at all. 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

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

Upvotes: 1

Eric Hotinger
Eric Hotinger

Reputation: 9316

Pretty straightforward, just use the number as the thing you want to switch on. Your else case becomes the default case.

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

Upvotes: 2

Related Questions