2

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’;
4
  • 1
    Please show any attempt at a switch statement you've made, along with any problems you've encountered. Commented Oct 29, 2015 at 19:17
  • 1
    java switch statement docs Commented Oct 29, 2015 at 19:17
  • Note: These if blocks are not nested. They are chained. Commented Oct 29, 2015 at 19:26
  • For something like this he could also use a character array over a switch statement. char [] chars = {'A','B','C','D'}; int index = num1-5; myChar = chars[index]; Commented Oct 29, 2015 at 19:30

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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’;
}

1 Comment

This would return either A or D only. You should change the values of your case statements.
0

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';
}

1 Comment

It's good that you showcase a fairly new feature in Java, but I think it'd be worth to also add an example for pre-java 12.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.