Setin
Setin

Reputation: 5

java program runs both the if and the else statemets

I am quiet a newbie when it comes to programming and I am trying to write something similar to a chess program. Here is the part of code with which I am having trouble:

if (chosenCollumn == tempCollumn && ((chosenRow == tempRow + 1) || (chosenRow == tempRow + 2))){
        board[chosenRow][chosenCollumn ] = movingPiece;
        board[tempRow][tempCollumn] = null;
}
else {
        System.out.println("invalid move");
}

The problem is that the program runs both the if statement AND the else statement. It moves the piece to a new place and "removes" it from the previous place. And after that it stil prints "invalid move". Now I'm not an expert, but this shouldnt be possible right? What am I doing wrong?

Upvotes: 0

Views: 583

Answers (1)

dan1st
dan1st

Reputation: 16486

In an if-else structure, the JVM will not execute both the if and the else statements.

It seems like you watched over something.

I can think of 2 Scenarios

  • You run the code multiple times and the condition is true once(if gets executed) and false the other time(else gets executed) (this seems to be it, see the comments)
  • The code is executed once but you have some code at another point of your program that does the same thing and makes you think that both statements are executed.

In any case, debugging would help :)

Upvotes: 2

Related Questions