jeudi 2 mars 2017

Java: If condition is false and still executes

I've tried looking but didn't find an answer anywhere, and I don't see where is the problem.

when executing the program, the value of "calc!=odd" is false, and i've even made the console print it's value to make sure, and right after, the if statement executes and returns false to main

did the same thing with "calc!=even" with a different size matrix

I really don't know what is the problem, hope someone can clarify, thanks.

public class snake {

public static void main(String[] args) {
    int[][] matrix = new int[5][7];
    putNumbers(matrix);
    printMatrix(matrix);
    System.out.println("the matrix is snake? " + isSnake(matrix, matrix.length));
}

private static Boolean isSnake(int[][] matrix, int length) {
    length--;
    int calc, odd=-1,even=1;
    for (int i = 0; i < (matrix[length].length - 2);i++) {
        calc=matrix[length][i] - matrix[length][i + 1];
        if(length%2==0)
        {
            System.out.println(calc!=odd);  //value is false - prints
            if (calc!=odd);                 //executes anyway even when false
            {
                return false;
            }
        }
        else
        {
            System.out.println(calc!=even);
            if (calc!=even);
            {
                return false;
            }
        }
    }
    if (length == 0)
        return true;
    return isSnake(matrix, length - 1);
}

private static void putNumbers(int[][] matrix) {
    int n = 1;
    for (int i = 0; i < matrix.length; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < matrix[i].length; j++, n++) {
                matrix[i][j] = n;
            }
        } else {
            for (int j = matrix[i].length - 1; j >= 0; j--, n++) {
                matrix[i][j] = n;
            }
        }
    }

}

private static void printMatrix(int[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++)
            System.out.printf("%d\t", matrix[i][j]);
        System.out.println();
    }
    System.out.println();

}

}

Aucun commentaire:

Enregistrer un commentaire