vendredi 20 décembre 2019

Why is this 'if' statement printing "Impossible"?

public class Experiment5 {

private static int countChar(String string, char c) {
    int count = 0;
    for (int i = 0; i < string.length(); i++) {
        if (string.charAt(i) == c) {
            count++;
        }
    }
    return count;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();

    if (countChar(input, '_') > 0){
        if ((countChar(input, 'X') - countChar(input, '0') >= 2) || (countChar(input, '0') - countChar(input, 'X') >= 2) ) {
            System.out.println("Impossible");
            return;
        }
        System.out.println("Game not finished");
    }
}

Input:
XO_OOX_X_

I believe that the result should be "Game not finished" because the difference between the counts of 'X' and 'O' is 0.
Then why is this returning "Impossible"?

Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire