2D数组,用于检查char值是否在行或列中出现一次

时间:2015-02-28 05:46:06

标签: java

我有一个2D数组,我正在尝试检查字符值是否只在列和行中出现一次。代码很简单。这就是我所拥有的:

package MultiDimensionalArrays;

public class latinSquare {

    public static void main(String[] args) {

        char[][] arrayRefVar = {
                {'A', 'B','C','D'},
                {'B', 'A','D','C'},
                {'C', 'D','B','A'},
                {'D', 'C','A','B'},
        };

        if (Column(arrayRefVar) && Row(arrayRefVar)) {
            System.out.println("The input array is a Latin square");
        }
        else {
            System.out.println("Wrong input: the letters must be from A to C ");
        }
    }

    public static boolean Column(char[][] m) {

        boolean isLatinSq = true;

        char[] tempColumn = new char[m.length];

        for (int i = 0; i < m.length; i++) {

            for (int j = 0; j < m.length; j++) {
                tempColumn[j] = m[j][i];
                }
            if (!checkColumn(tempColumn)) {
                isLatinSq = false;
                break;
            }
            for (int j = 0; j < m[0].length; j++) {
                tempColumn[j] = 0;
                }
        }

        return isLatinSq;
    }

    public static boolean checkColumn(char[] a) {

        boolean isFalse = false;

        for (int i = 0; i < a.length - 1; i++) {
            for (int j = a.length - 1; j > i; j--) {
                if (a[j] == a[i]) {
                    isFalse = true;
                    break;
                }
            }
        }
        return isFalse;
    }

    public static boolean Row(char[][] m) {

        boolean isLatinSq = true;

        char[] tempRow = new char[m[0].length];

        for (int i = 0; i < m.length; i++) {

            for (int j = 0; j < m[0].length; j++) {
                tempRow[j] = m[i][j];
                }
            if (!checkRow(tempRow)) {
                isLatinSq = false;
                break;
            }
            for (int j = 0; j < m[0].length; j++) {
                tempRow[j] = 0;
                }
        }

        return isLatinSq;
    }

    public static boolean checkRow(char[] b) {

        boolean isFalse = false;

        for (int i = 0; i < b.length - 1; i++) {
            for (int j = b.length - 1; j > i; j--) {
                if (b[j] == b[i]) {
                    isFalse = true;
                    break;
                }
            }
        }
        return isFalse;
    }
}

我似乎无法做到这一点,有人看到我的错误吗?

1 个答案:

答案 0 :(得分:0)

checkColumn(tempColumn)返回false,并且!相反。 所以它变成了真的......对于行函数也一样。

    if (checkColumn(tempColumn)) {
      isLatinSq = false;
      break;
    }