I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? 🙂
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
You’re switching on x which is a String – unless you’re using Java 7, you can’t use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you’re checking what it starts with) and returns a boolean, which you can’t switch on either.
UPDATE Correcting your code to do what I think you’re trying to do:
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur – then you don’t need to do the switch at all.
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.