如何检查二维数组是否只包含数字

时间:2018-04-10 15:31:43

标签: java arrays

我有一个只有数字的二维String数组;

System.out.println(Arrays.deepToString(temp));
[[1, 3, 1, 2], [2, 3, 2, 2], [5, 6, 7, 1], [3, 3, 1, 1]]

我需要检查数组是否只包含数字,否则我会抛出异常。

System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]*")); - return false                           
System.out.println(Arrays.deepToString(temp[0]).matches("[0-9]+")); - return false

据我所知,代码表示数组不包含数字,因为当转换为char时,数组就像:

[[, [, 1, ,,  , 3, ,,  , 1, ,,  , 2, ], ,,  , [, 2, ,,  , 3, ,,  , 2, ,,  , 2, ], ,,  , [, 5, ,,  , 6, ,,  , 7, ,,  , 1, ], ,,  , [, 3, ,,  , 3, ,,  , 1, ,,  , 1, ], ]]

如何检查它是否仅包含数字?

2 个答案:

答案 0 :(得分:2)

首先应该循环遍历数组。由于每个元素都是一个数组,因此循环遍历它。然后为每个元素(应该是一个String)检查它是否是你想要的。

循环遍历数组数组:

boolean arrayIsCorrect = true; //flag to know if array is correct
for(int i=0; i<array.length; i++) { //loop through the array of arrays
    for(int j=0; j<array[i].length; j++) { //loop through the sub-array array[i]
        if(!isCorrect(array[i][j])) {
            arrayIsCorrect = false;
            break; //optimization not required
        }
    }
    if(!arrayIsCorrect) { //optimization not required
        break;
    }
}
System.out.println("Is the array correct ? " + arrayIsCorrect ); //print the result

在您的问题中,您不清楚您是否希望元素为数字或数字。如果是数字,则函数isCorrect()应如下所示:

public boolean isCorrect(String s) {
    return s.matches("[0-9]");
}

如果是数字,请检查此answer

答案 1 :(得分:0)

我会创建一个检查它是否为数字的函数。

这样的事情:

for(int i = 0; i < array.size();i++){
    for(int j = 0; j < array.size();j++){
        if(temp.isNumeric(temp[i][j] == false)
        break;
    }
}

public static boolean isNumeric(String value) {
    boolean result;
    try {
        Integer.parseInt(value);
        result = true;
    } catch (NumberFormatException excepcion) {
        result = false;
    }
    return result;
}