So I am trying to learn Java, and have been writing a basic program based off of the 21 matches game; in which each player takes turns taking 1,2 or 3 matches. The player to take the last match loses.
It was going well until I found that when the user was about to win, the program wouldn't enter the final else if statement; it would skip over it and come back to the user, without the computer having taken any matches. Attached is the method I have written for the computers turn.
public static int ComputerPlays(int matches){ //Method for the computers turn
int matchesTaken = 0;
if (matches > 7){ matchesTaken = new Random().nextInt(3)+1; }
else if (matches > 4 && matches < 8){ matchesTaken = matches - 4; }
else if (matches < 5){ matchesTaken = matches - 1; }
else if (matches == 1){ matchesTaken = 1; }
System.out.println("Computer takes " + matchesTaken + " matches");
return(matches - matchesTaken);
}
The line else if (matches == 1){ matchesTaken = 1; } is where I'm having a problem. Any help would be appreciated.
P.S. I realize that I could turn the else if into an else statement, but the main thing is I want to learn what the problem is, not just get around it.
Aucun commentaire:
Enregistrer un commentaire