Stephen Ryan
Stephen Ryan

Reputation: 173

Java method returns int that can't be compared to another int (Android Studio)

First off, these are ints, not Integers. I want to get a variable from another class and compare it to a value, like so:

Log.v("xx", "" + boardAdap.getPieceNumber());
int pieceNumberInt = boardAdap.pieceNumber;

if (pieceNumberInt == 32) {
    Log.v("xx", "int comparison worked");
}

int pieceNumberMethod = boardAdap.getPieceNumber();

if (pieceNumberMethod == 32) {
    Log.v("xx", "method comparison worked");
}

So, I want to get the pieceNumber variable from the boardAdap class, and check if it is equal to 32. If it is, it prints the stuff in Log in the console.

The boardAdap method:

int pieceNumber;
int pieceNumberIncrement;

public int getPieceNumber() {
    for (int i = 0; i < 64; i++)  {
        if (board.getPiece(Square.squareAt(i)).name() != "NONE") {
            this.pieceNumberIncrement++;
        }
    }
    this.pieceNumber = pieceNumberIncrement;
    return pieceNumber;
}

This iterates through an enum called Square, and increments pieceNumberIncrement if the value is not "NONE". However, when I run this, the output is:

32
int comparison worked

So, why does the second if condition fail, if getPieceNumber() returns an int? It also fails when I use an Integer wrapper, or convert pieceNumberMethod to a string and then to an Integer, and other methods.

Also, should I change getPieceNumber() to just update the pieceNumber instead, and reference only that?

Additionally, if pieceNumberMethod is used in a for loop like:

for (int i = 0; i < pieceNumberMethod; i++) {
}

The for loop will never stop.

Thanks!

Upvotes: 0

Views: 91

Answers (2)

bichito
bichito

Reputation: 1426

The problem is comparing the strings. You need equals("NONE")

String none = new String("NONE");
int count = 32;

System.out.println(count);
for (int i = 0; i < 64; i++)  {
    if (none != "NONE") {
        count++;
    }
}
System.out.println(count);

If you run this code it will print different values for "count" despite value of "none"

Upvotes: 1

Ziya ERKOC
Ziya ERKOC

Reputation: 839

You are basically calling getPieceNumber twice so in the second call the number changes.

int pieceNumberMethod = boardAdap.getPieceNumber();
Log.v("xx", "" + pieceNumberMethod);
int pieceNumberInt = boardAdap.pieceNumber;

if (pieceNumberInt == 32) {
    Log.v("xx", "int comparison worked");
}


if (pieceNumberMethod == 32) {
    Log.v("xx", "method comparison worked");
}

Try calling method once.
Hope that works!

Upvotes: 1

Related Questions