繁体   English   中英

如果语句对象布尔不起作用

[英]If statement Object boolean not working

我正在尝试使用另一个类中的另一个对象来检查某个人的年龄,由于某种原因, 无论如何,areThe boolean返回false。 我实现的以下代码是

  public class main {    
    public static void main(String[] args){    
      Obj object = new Obj();    
      object.areTheyOldEnough();

      if(object.areTheyOldEnough() == true){
          System.out.println("They are old enough!");
      }else{
          System.out.println("They are not old enough!");
      }
    }
}

public class Obj {
    private int age = 15;
    private boolean areThey;

    public boolean areTheyOldEnough() {
        if (age > 12) {
            boolean areThey = true;
        }
        return areThey;    
    } 
} 

您的问题称为阴影 这里:

最内在的声明:

if (age > 12) {
  boolean areThey = true;

简直是错误的,应改为:

areThey = true;

代替。 关键是:您正在声明一个具有该名称的变量,并将其值设置为true 但是,当if块为“ left”时,该变量就消失了……返回的是obj类中的areThey 字段的值。 并且那个仍然具有其初始默认值false

除此之外, 命名是代码中的实际问题。 使用符合A)符合Java编码标准的名称; 因此,例如,类名以UpperCase开头; B) 意味着什么。

换句话说:名称Object毫无意义(创建另一个名称与java.lang.Object类名称冲突)。 最好称它为“ testInstance”或类似的名称-如前所述:使用表示含义的名称。

您有两个同名的布尔变量-一个是局部变量,您可以在方法中设置该变量(在if块内部),另一个是要返回的实例变量。

您不需要任何布尔变量,只需编写:

public boolean areTheyOldEnough() {
    return age > 12;
}

您混合了字段和局部变量的可见性

public class obj {

public int age = 15;
public boolean areThey; //initialized to false as default value for boolean

public boolean areTheyOldEnough() {
   if (age > 12) {
       boolean areThey = true; //create new local variable with the same name as field, 
                               // but visible just in scope of if-block
    }
    return areThey; // return value from field
}

更正您的代码,如下所示:

public class main {

public static void main(String[] args){

  obj Object = new obj();

  if(obj.areTheyOldEnough()){
      System.out.println("They are old enough!");
  } else{
      System.out.println("They are not old enough!");
  }
}

和您的obj类将是:

public class obj {
public int age = 15;
// it is not required, but if you need for other methods,
// you can define it
public boolean areThey;

public boolean areTheyOldEnough() {
    return age > 12;
    // or if you need set variable areThey, so use following codes
   /*
      areThey = age > 12;
      return areThey;
   */
}

暂无
暂无

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

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