Chase Zandvliet
Chase Zandvliet

Reputation: 11

I'm having some trouble with my switch statement

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

Answers (3)

Abi
Abi

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You are trying to switch on a String, while the cases are ints. You need to parse the string before passing it to switch:

String answer1 = in.nextLine();
switch (Integer.parseInt(answer1)) {
    ...
}

Upvotes: 3

Dynelight
Dynelight

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

Related Questions