(beginner) Switch Statement
Hello, I would like to ask a question regarding a switch case of mine. I am new to Java(have dabbled in c++ a little though.)
In one of my classes I have a method designed to take a character as a parameter and return a string based on the appropriate case.
The problem is the string that is always being returned is the default "INVALID", could someone point me in the appropriate direction? I checked the java tutorial but it didn't offer me much help, is there a problem with comparing integer literals / character literals on the same switch test condition?
Code :
private String GetNumber(char number)
{
String numberString = null;
if(Character.isLetter(number))
{
Character.toUpperCase(number);
}
switch(number)
{
case 'A': numberString = "Ace";
break;
case 2: numberString = "two";
break;
case 3: numberString = "three";
break;
case 4: numberString = "four";
break;
case 5: numberString = "five";
break;
case 6: numberString = "six";
break;
case 7: numberString = "seven";
break;
case 8: numberString = "eight";
break;
case 9: numberString = "nine";
break;
case 1: numberString = "ten";
break;
case 'J': numberString = "jack";
break;
case 'Q': numberString = "Queen";
break;
case 'K': numberString = "King";
break;
default : numberString = "INVALID";
break;
}
return numberString;
}
Re: (beginner) Switch Statement
One thing that jumps out is your case numbers. You have them as ints but your switch statement variable is a char. You numbers should be '2' or '3' etc...
also you may have to take the input as a string and use the charAt() method.
Re: (beginner) Switch Statement
Quote:
Originally Posted by
mwr76
One thing that jumps out is your case numbers. You have them as ints but your switch statement variable is a char. You numbers should be '2' or '3' etc...
also you may have to take the input as a string and use the charAt() method.
I actually did use the charAt method to get that value.
Also the single quotes around my cases solved the problem. Thread marked as solved and a Thanks to you (;