简体   繁体   中英

How can I replace “true” and “false” in java?

I need change the values for boolean variables, for example:

Change this:

boolean x = true;
System.out.print(x); //console: true

For this:

boolean x = true;
System.out.print(x); //console: 1

This is my code:

final boolean[] BOOLEAN_VALUES = new boolean [] {true,false};
for (boolean a : BOOLEAN_VALUES) {
                boolean x = negation(a);
                String chain = a+"\t"+x;
                chain.replaceAll("true", "1").replaceAll("false","0");
                System.out.println(chain);
        }

negation is a method:

    public static boolean negation(boolean a){
            return !a;
        }

As you can see, I try using .replaceAll , but its not working, when I executed, this is the output:

  a ¬a ---------------- true false false true 

I really don't see my error.

System.out.println(x ? 1 : 0); should do the trick , basically 1 if true, and 0 otherwise

There are 2 ways:

The if-else one, which checks if x is true or false .

if (x) {
    System.out.println(1);
} else {
    System.out.println(0);
}

Note: if (x) is the same as if (x == true) .

The ternary one:

System.out.println(x ? 1 : 0);

Which checks if x is true if so, it prints 1 else it prints 0 . I recommend the ternary one as it's shorter and helps for code clarity.

Now i found the solution, i just missed matching the variable:

chain = chain.replaceAll("true", "1").replaceAll("false","0");

Now this is solved, thanks for your answers.

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