繁体   English   中英

为什么静态变量在其他类中不起作用?

[英]Why the static variable doesn't work in other class?

我在执行android项目时遇到问题...我在“ A.java”中声明了六个变量,如下所示。

public static int a = -1;
public static int b = -1;
public static int c = -1;
public static int d = -1;
public static int e = -1;
public static int f = -1;

我设置为,如果readMessage等于s1 ...,则a =0。然后继续。 readMessage,s1,s2,s3,s4,s5和s6是字符串。

 if(readMessage.equals(s1)){
                   a=1;
                }
                else if(readMessage.equals(s2)){
                   b=1;
                }
                else if(readMessage.equals(s3) ){
                   c=1;
                }
                else if(readMessage.equals(s4)){

                   d=1;
                }
                else if(readMessage.equals(s5)){

                   e=1;
                }
                else if(readMessage.equals(s6)){
                   f=1;
                }

现在在MainActivity.java中,我编写如下代码。 但这不起作用! 图像不变。

ImgPhoto = (ImageView)findViewById(R.id.logoImageView);

if((A.a) == 1){ImgPhoto.setImageResource(imgId[0]);}
    else if((A.b) == 1){ImgPhoto.setImageResource(imgId[1]);}
    else if((A.c) == 1){ImgPhoto.setImageResource(imgId[2]);}
    else if((A.d) == 1){ImgPhoto.setImageResource(imgId[3]);}
    else if((A.e) == 1){ImgPhoto.setImageResource(imgId[4]);}
    else if((A.f) == 1){ImgPhoto.setImageResource(imgId[5]);}

谁能帮我? 我在互联网上搜索,但没有找到任何解决方案...。感谢您的帮助!

原始数据类型INT的默认值为0。

您可以在这里查看文档

因此,所有字段AF的值都为0。

来自甲骨文

声明字段时,不一定总是需要分配值。 编译器会将已声明但未初始化的字段设置为合理的默认值。 通常,此默认值将为零或null,具体取决于数据类型。 但是,通常认为依赖于此类默认值是不好的编程风格。

因此,所有static变量A.java将设为zeronulljvm和第一if语句总是为真

最好的解决方案是将它们设置为未使用的值,例如-1

public static int a=-1;
public static int b=-1;
public static int c=-1;
public static int d=-1;
public static int e=-1;
public static int f=-1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM