If-else 工作,切换不 [英] If-else working, switch not

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

问题描述

我正在制作一个应用程序,它有一个带有文本的图像网格,每个图像都会打开一个不同的活动.它工作正常,但只是出于设计目的,我想用 switch statements 替换我的 if-else statements (我假设我可以这样做)但是它不起作用.现在我在每个图像上设置标签的工作代码是:

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);    

但是当我这样做的时候,那个标签是我定义的最后一个标签(在我的例子中它是四个").对于每个对象,我也有一个类似的代码,以使用 position 变量启动一个不同的 intent 变量,但是这样做相反,并且使每个意图都等于第一个意图.我的语法是错误的还是对我的情况不起作用?

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?

推荐答案

case中的每条语句后都需要break;,否则执行流程向下(所有case在你想要的那个下面也会被调用),所以你总是会得到最后一个案例.

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; 
}

这里是 官方教程 解释何时何地使用 break;.

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

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

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