简体   繁体   中英

boolean doesn't set to true in Java

Here am trying to change the status of 'stat' which isn't working

    public class controller {

        public static void main(String args[]){{

            final AjaxR re = new AjaxR();
            re.setMal("qw");
            if (re.getMal() != null) {
                re.setStat(true);
            }

            if(re.isStat()){
              System.out.println("Hello");
        }
    }



public class AjaxR {

    boolean stat;
    String mal;

    public boolean isStat() {
        return stat;
    }

    public void setStat(final boolean stat) {
        this.stat = stat;
    }

    public String getmal() {
        return mal;
    }

    public void setMal(final String mal) {
        this.mal = mal;

    }

Here re.stat isn't setting to true. Unless I forcefully execute re.setStat(true) manually in debug mode, it is not changing.

There are multiple syntactic problems with your code:

  • Two opening { after your main method header;
  • getMal() is the wrong case, it doesn't match your method getmal() in AjaxR ;
  • There is no closing brace for your controller class;
  • There is no closing brace for AjaxR either.

However, when those errors are fixed (I will leave that as an exercise for you to complete!), your code behaves as you expect - "Hello" is printed and stat is definitely set to true.

I copied your code into eclipse and was able to easily find the rest of your errors. You did not have the correct amount of opening and closing braces, plus you named you method getmal() instead of getMal() . All these typos and errors can easily be detected if you use a proper IDE.

After inserting the correct amount of braces and fixing all the typos, the following code works and prints out Hello :

public class controller {

    public static void main(String args[]){

        final AjaxR re = new AjaxR();
        re.setMal("qw");
        if (re.getMal() != null) {
            re.setStat(true);
        }

        if(re.isStat()){
            System.out.println("Hello");
        }
    }
}



public class AjaxR {

    boolean stat;
    String mal;

    public boolean isStat() {
        return stat;
    }

    public void setStat(final boolean stat) {
        this.stat = stat;
    }

    public String getMal() {
        return mal;
    }

    public void setMal(final String mal) {
        this.mal = mal;
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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