-2

I am having an issue with a worksheet online and I was wondering if someone could show me the correct code for my problem and also explain as to why it should be written like that.

Here is the question on the worksheet I am on:

This time let's try a switch statement to convert the characters on a telephone dialpad to the corresponding digits. Recall that

'A', 'B', 'C' map to 2 'D', 'E', 'F' map to 3 'G', 'H', 'I' map to 4 'J', 'K', 'L' map to 5 'M', 'N', 'O' map to 6 'P', 'Q', 'R', 'S' map to 7 'T', 'U', 'V' map to 8 'W', 'X', 'Y', 'Z' map to 9

Write a switch statement that sets the variable digit to the appropriate digit, given the character letter. Set digit to 0 for any other character not listed in the mapping above.

Here is my attempt at solving the issue using a switch statement:

switch (letter)
{

case 'A' || 'B' || 'C' : digit = 2;

break;

case 'D' || 'E' || 'F' : digit = 3;

break;

case 'G' || 'H' || 'I' : digit = 4;

break;

case 'J' || 'K' || 'L' : digit  = 5;

break;

case 'M' || 'N' || 'O' : digit = 6;

break;

case 'P' || 'Q' || 'R' || 'S' : digit = 7;

break;

case 'T' || 'U' || 'V' : digit = 8;

break;

case 'W' || 'X' || 'Y' || 'Z' : digit = 9;

break;

default : digit = 0;

break;
}

How should I do this switch statement and what should be corrected??

I get the error message: I found more elements than I expected, here:

1
  • You cannot use those ORs in a case statement like that. Google for the syntax of the switch statement: you need a "case" for each value. Commented Jun 17, 2013 at 15:20

1 Answer 1

9

It should be:

case 'A': case 'B': case 'C':
    // do something

And as code styles vary, you may also see:

case 'A':
case 'B':
case 'C':
    // do something

This does the same thing.

Side node: 'A' || 'B' is not legal since || is a logical boolean operator which expects booleans on both sides; but here what you have are characters.

Sign up to request clarification or add additional context in comments.

10 Comments

Here is a short snippet of what I have changed it to: switch (letter) { case 'A' : case 'B' : case 'C' : digit = 2; break; Is this correct or not as I am still getting the same error??
Seems good, whats the error?
The error was I found more elements than I expected, here: if you want to look at the worksheet it is here : labs.web-ide.org:8080/Web_IDE/#Lab-http://labs.web-ide.org/… You just have to click on the switch section :)
yeah, thats not a real java exception, thats something the "web-IDE" is producing, using code that works correctly in a "real" IDE in it gives errors. Try using an IDE like netbeans or eclipse
I have eclipse its just this is the worksheet I use for my online course :) But if I were to use the code above that I put in for all cases then it would work?? If so awesome!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.