0

I have this code:

String Tunet = intent.getStringExtra("Tunet");

if (Tunet.equals("Yes")  ){
    tv22.setText(" okay");
} else {
    tv22.setText("please answer");
}

I want to do this code, in a switch statement, something like this but I don't know how.

switch(Tunet.equals)
case: Yes
   // do something
case: No
   // do something
case: I don't know
   // do something

and continue it like this, how to do this? Thanks for help.

michaldo
  • 4,195
  • 1
  • 39
  • 65
Tin_Ram
  • 99
  • 1
  • 11

5 Answers5

2

Use else if

if (Tunet.equals("Yes")  ){
        tv22.setText(" okay");
    } else if (Tunet.equals("No")){
        tv22.setText("please answer");
    }  else if (Tunet.equals("I don't know ")){
        tv22.setText("TEXT");
    }
Stanislav Bondar
  • 6,056
  • 2
  • 34
  • 46
2

If you are compiling your project with Java SE 7+, you can do switch directly on your String so this is a valid code

switch(Tunet){
    case "Yes":
    break;
    case "No":
    break;
    default:
    break;
}

See more here

Community
  • 1
  • 1
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
1

here is a work around for your problem, may that help.

    String Tunet = intent.getStringExtra("Tunet");
    int _Case = -1;
    if (Tunet.equals("yes")) {

        _Case = 1;
    } else if(Tunet.equals("no")) {
        _Case = 2;
    }

    switch (_Case){
        case 1:
        // code if if Tunet is yes
            break;
        case 2:
            //code for no
            break;
    }
Moubeen Farooq Khan
  • 2,875
  • 1
  • 11
  • 26
1

Before JDK 7 release it was not possible to use String as argument in switch. Oracle realized this shortcoming and if you are working on jdk 7.0+ , you can write the code as:

switch(Tunet.equals)
{
case: Yes
      // do something
      break;
case: No
      // do something
      break;
default: I don't know
      // do something
}
Karan
  • 2,120
  • 15
  • 27
  • It won't but this is just the skeleton or the idea. Why would I write working code for free ;) – Karan May 01 '15 at 21:04
  • Don't know, but how can you just copy that code from the question and say it works in Java 7 when clearly it won't. Anyway, fair play for getting an upvote for this. – ci_ May 01 '15 at 21:07
1

From JDK 7.0 you can simply,

switch(intent.getStringExtra("Tunet")){
    case "A":
    break;

    default:
    break; 
} 
noman404
  • 928
  • 1
  • 8
  • 23