If-else working, switch not

后端 未结 9 1803
一向
一向 2020-12-03 14:44

I am making an app that has a grid of images with text and each one opens a different activity. It works fine but just for design purposes I want to replace my if-else

相关标签:
9条回答
  • 2020-12-03 15:31

    Don't forget to put break; after each case: like that:

    switch(position){
    case 0:
       textView.setText(R.string.zero);    
       break;
    case 1:
       textView.setText(R.string.one);
       break;
    case 2:
       textView.setText(R.string.two);    
       break;
    case 3:
       textView.setText(R.string.three);
       break;
    case 4:
       textView.setText(R.string.four);  
       break;
    }
    
    0 讨论(0)
  • 2020-12-03 15:37

    You need to use break statement after eace case operations. In a switch-case statement if you dont use a break statement then all the cases after that specific one will be executed also

    case 0:
       textView.setText(R.string.zero);    
       break;
    
    0 讨论(0)
  • 2020-12-03 15:44

    In the Switch-case statements, you need to put break; after each case.

    switch(position){
    case 0:
       textView.setText(R.string.zero);    
       break;
    case 1:
      textView.setText(R.string.one);
      break;
    case 2:
      textView.setText(R.string.two);    
      break;
    case 3:
      textView.setText(R.string.three);
      break;
    case 4:
      textView.setText(R.string.four);  
      break;
    default:
        System.out.println("not available");
    }
    

    Also you need to put default: at last, because when all case are wrong that time perform default: action.

    In the switch-case statement not forgot about break; and default action.

    0 讨论(0)
提交回复
热议问题