Reputation: 11
Ok so I've been programming for a short time and I've already started making pretty nice programs. But when it comes to switches it's always luck when they actually work. I wrote this switch statement:
String answer1 = in.nextLine();
switch (answer1)
{
case 1:
System.out.println("...");
break;
case 2:
System.out.println("...");
break;
case 3:
System.out.println("...");
break;
}
And the switch labels next to the cases all said 'error cannot convert from int to string' could someone please help. Thanks Noob programmer~ Chase
Upvotes: 0
Views: 60
Reputation: 1345
Strings in switch are supported only from Java 7.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
If you are using Java 7 and above then
switch (answer1)
{
case "1":
System.out.println("...");
break;
case "2":
System.out.println("...");
break;
case "3":
System.out.println("...");
break;
else you have to convert it to int as shown in the answer by @dasblinkenlight
Upvotes: 1
Reputation: 726479
You are trying to switch on a String
, while the cases are int
s. You need to parse the string before passing it to switch
:
String answer1 = in.nextLine();
switch (Integer.parseInt(answer1)) {
...
}
Upvotes: 3
Reputation: 2162
You might need to verify the version of Java you're using. This was not possible on older versions of Java.
See: Why can't I switch on a String?
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
That is, if you intend to switch on String. See the below answer (@dasblinkenlight) if you do indeed expect an integer (You need to parse it).
Upvotes: 0