Java 2d数组,方形测试



我得到了一个数组(a2d),我需要确定每一行和每一列是否与其他行和列具有相同数量的元素。如果是,那么我将布尔值isSquare设置为true。

我已经想出了以下代码,但它不喜欢它,也没有给我任何关于如何改进它的建议。

for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
    if(a2d.length == a2d[row].length)
        isSquare = true;
    else
        isSquare = false;
}

我测试这个的方法是错误的还是有更好的方法?

不需要2个循环,你应该能够做这样的事情(我不打算给出代码,因为这是家庭作业)

1. Save the length of the array (a2d.length)
2. Loop over all the rows
3. Check to see if the given row has the same length
4. if Not return false 
5. if you reach the end of the loop return true
for (int i = 0, l = a2d.length; i < l; i++) {
  if (a2d[i].length != l) {
    return false;
  }
}
return true;

您只需要确保二维数组的所有长度与一维数组的长度相同。

if(a2d.length == a2d[row].length)
    isSquare = true;
else
    isSquare = false;

如果最后一个元素通过,它将始终返回true。试试这个:

isSquare = true;
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
    if(a2d.length != a2d[row].length)
        isSquare = false;
}
  1. 保存阵列的长度(size.length)

  2. 在所有行上循环

  3. 检查给定行是否具有相同长度的

  4. 如果为true,则设置isSquare,否则为false,以控制循环

  5. 如果你到达循环的末尾并且isSquare返回true否则返回false

    private static boolean isSquare(Object[][] matrix){
    boolean isSquare = true;
    //Save the length of the array
    int size = matrix.length;
    //Loop over all the rows and Check to see if the given row has the same length
     for (int i = 0; i < size && isSquare; i++) {
        isSquare = size == matrix[i].length;
     }
    return isSquare;
    }
    

或不是纯粹的fori

private static boolean isSquare(Object[][] matrix){
    //Save the length of the array
    int size = matrix.length;
    //Loop over all the rows and Check to see if the given row has the same length
    for (int i = 0; i < size; i++) {
        if(size != matrix[i].length)
            return false;
    }
    return true;
}

具有针对的增强功能

private static boolean isSquare(Object[][] matrix){
    //Save the length of the array
    int size = matrix.length;
    //Loop over all the rows and Check to see if the given row has the same length
    for (Object[] objects : matrix) {
        if (size != objects.length)
            return false;
    }
    return true;
}

最新更新