【问题标题】:Boolean value changed but not recognized by if statement布尔值已更改但 if 语句无法识别
【发布时间】:2020-02-16 12:04:21
【问题描述】:

我有两个班级,“class1”和“class2”。 当我在“class1”中初始化一个名为“test”(true)的布尔值并在“class2”中的 if 语句中询问它的值时,一切正常。 但是,一旦我在方法中将值从“test1”更改为 false,它就无法识别“class2”中 if 语句的更改。

我的目标是,一旦奖励视频结束,布尔值就会发生变化,并且 class2 中的 if 语句可以识别它。

类1:

public boolean test1= true; //This is recognized by the if-statement in class2

    ...

    @Override
    public void onRewardedVideoAdRewarded(Placement placement) {
        test1 = false; //this is getting ignored by the if-statement in class2
    }

类2:

Class1 class1 = new Class1();

if(class1.test1){
    // Do something
}else{
    // Do something else
}

希望你能帮助我,谢谢。

【问题讨论】:

  • 您正在创建class1 的新实例,然后在调用onRewardedVideoAdRewarded 之前检查test1 的值。
  • @AndyTurner 我该怎么做才对?
  • @MartinZeitler 你能就我的情况向我解释一下吗?没看懂
  • 你怎么知道你的代码在调用onRewardedVideoAdRewarded?我不认为它到达那里

标签: java android class if-statement boolean


【解决方案1】:

如果您使用静态变量,您的问题就会得到解决。 制作一个这样的类:

public class MyStatics {
public static boolean test1=true;

}

现在将第 1 类更改为:

 @Override
public void onRewardedVideoAdRewarded(Placement placement) {
    test1 = false; 
}

保持 2 级不变。

注意:

静态变量随处可访问,无需重新定义。

你的问题是什么?

class2 忽略了class1,因为当你使用“new”class1 时,简单来说,就像你的所有设置都恢复为默认值,而你的默认值是public boolean test1= true;

【讨论】:

    【解决方案2】:

    Java 是一种所谓的面向对象的语言。对于在一个名为“Movie”的类中定义的所有“静态”成员,无论创建了多少电影对象,都有一个成员。但对于普通(非静态)成员,每个创建的对象都有一个。

    所以,当您编写Class1 class1 = new Class1(); 时,您正在创建一个新的 class1 对象,因此,是其中每个非静态成员的副本。这意味着您的运行时中至少有 2 个 class1 对象的实例,当您说 test1 = false 时,您正在更新 test1 字段,该字段是不同对象的一部分,而不是另一个类正在读取的对象。

    解决方案?将 class1 的实例传递给 class2 的某个方法(或构造函数),或者可能使用静态字段或其他解决方案;您没有粘贴足够的代码来对这里的最佳方法做出有意义的猜测。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2020-07-30
      • 2019-05-06
      • 2017-09-05
      • 2020-02-15
      • 1970-01-01
      • 2016-11-20
      相关资源
      最近更新 更多