Need a bit of assistance with Java operators, getting a "bad operand type int for unary operator" error

Viewed 63

I have a bit of code for which I am trying to figure out the logic. In this bit of code, I have three booleans:

  • hasAccount

  • isInactive

  • trackInactive

In this situation, I only want to do something if:

A user has an account OR a user has an account, their account is active, or their account is not active and I am not tracking inactive accounts.

Initially, I thought it would be like this:

if(hasAccount ^ (hasAccount && (!isInactive || !trackInactive))){
    // Do something here ...
}

I tried to write a bit of code to test all inputs to see which condition would give me the correct output. Here is what I have:

import java.util.Locale;
public class BoolTest {
    public static void main(String[] args){
        boolean[] boolArray = {false,true};

        // WHERE:
        // A -or- i = hasAccount
        // B -or- j = isInactive
        // C -or- k = trackInactive

        System.out.println("+---+---+---++---+");
        System.out.println("| A | B | C || X |");
        System.out.println("+---+---+---++---+");
        for(int i=0; i<boolArray.length; i++){
            for(int j=0; j<boolArray.length; j++){
                for(int k=0; k<boolArray.length; k++){
                    System.out.println(String.format(Locale.US, "| %s | %s | %s || %s |", i, j, k, ((i ^ (i && (!j || !k))))));
                }
            }
        }
        System.out.println("+---+---+---++---+---+---+");
    }
}

However, when I run this I get these errors:

error: bad operand type int for unary operator '!'
    System.out.println(String.format(Locale.US, "| %s | %s | %s || %s |", i, j, k, ((i ^ (i && (!j || !k))))));
                                                                                                ^
error: bad operand type int for unary operator '!'
    System.out.println(String.format(Locale.US, "| %s | %s | %s || %s |", i, j, k, ((i ^ (i && (!j || !k))))));
                                                                                                      ^

How can I fix my bit of test code so that it properly tests all the different conditions?

1 Answers

In Java, you cannot use the ! operator on an integral type. In c++, you can, because of implicit conversions between boolean types and integer types, but in Java, there is no such implicit conversion. A boolean type is just either true or false, and and integer type is just an integer, which is why the ! operator will not work on an int.

In your case, you can just replace the i, j, k values with boolArray[i], boolArray[j], boolArray[k] and that should work as you expected.

Related