2

I want to change this switch statement to if statement or while loop. How can I do that? Note this piece of code using Android Studio.

public void onClick(View v) {
    switch(v.getId()){
    case R.id.button:
        Log.v(TAG, "verbose");
        break;
    case R.id.button2:
        Log.d(TAG, "Debug");
        break;
    case R.id.button3:
        Log.i(TAG, "Information");
        break;
    case R.id.button4:
        Log.w(TAG, "Warning");
        break;
    case R.id.button5:
        Log.e(TAG,"Error");
        break;
    }
}
3
  • 2
    i dont understand the issue, instead of a switch just use if's Commented Oct 8, 2015 at 15:45
  • 2
    switch case here its an good choice why you want if...else Commented Oct 8, 2015 at 15:45
  • if is used to select bn 2 options and switch is used among multiple options.Also performance of switch is better in case of multiple option. Commented Oct 9, 2015 at 7:32

2 Answers 2

4

If you're using AndroidStudio, you could use intent

  1. Place your cursor on the switch keyword
  2. Press alt+enter (on Mac, not sure about Windows)
  3. Select Replace 'switch' with 'if'

Note: You could replace if to switch using the same method.

Sign up to request clarification or add additional context in comments.

Comments

3

I would suggest you to use existing switch statement, but if you really want if, you can do it like this:

 public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.button) {
        Log.v(TAG, "Verbose");
    } else if (id == R.id.button2) {
        Log.d(TAG, "Debug");
    } else if (id == R.id.button3) {
        Log.i(TAG, "Information");
    } else if (id == R.id.button4) {
        Log.w(TAG, "Warning");
    } else if (id == R.id.button5) {
        Log.e(TAG, "Error");
    }    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.