If-else working, switch not

后端 未结 9 1839
一向
一向 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: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.

提交回复
热议问题