如果其他的工作,切换不 [英] If-else working, switch not

查看:123
本文介绍了如果其他的工作,切换不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出一个应用程序,具有文本的图像的网格,每个打开不同的活性。它工作正常,但只是为设计目的,我想取代我的 if-else语句 switch语句(我假设我能做到),但是它不工作。现在我的工作code来设置每个图像上的标签是:

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 statements with switch statements (which I assume I can do) however it doesn't work. Right now my working code to set the label on each image is:

if(position == 0)
        textView.setText(R.string.zero);
    else if(position == 1)
        textView.setText(R.string.one);
    else if(position == 2)
        textView.setText(R.string.two);
    else if(position == 3)
        textView.setText(R.string.three);
    else if(position == 4)
        textView.setText(R.string.four);
    else if(position == 5)
        textView.setText(R.string.five);
ect....

我要使用:

switch(position)
case 0:
   textView.setText(R.string.zero);    
case 1:
   textView.setText(R.string.one);
case 2:
   textView.setText(R.string.two);    
case 3:
   textView.setText(R.string.three);
case 4:
   textView.setText(R.string.four);    

但是当我这样做,永远的标签是我定义的最后一个(在我的例子这将是四大)。我也有一个类似的code为每个对象然而,做启动不同的意图位置变量相反,使每一个意图等于第一个。是我的语法错误,或将本不适合我的情况的工作?

but when I did that ever label was the last one that I defined (in my example it would be "four"). I also have a similar code for each object to start a different intent with the position variable however that does the opposite and makes every intent equal to the first one. Is my syntax wrong or will this not work for my situation?

推荐答案

您需要突破; 后在情况下,每个语句,否则执行流下来(下面你希望也将获得那叫一个所有情况下),因此您总能获得最后一种情况。

You need to break; after each statement in a case, otherwise execution flows down (all cases below the one you want will also get called), so you'll always get the last 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; 
}

下面是官方教程解释时,当不使用突破;

Here's the official tutorial explaining when to and when not to use break;.

这篇关于如果其他的工作,切换不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆