【问题标题】:How to check if a two dimensional Array contains only digits如何检查二维数组是否仅包含数字
【发布时间】:2018-04-10 15:31:43
【问题描述】:

我得到了一个只有数字的二维字符串数组;

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, ], ]]

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

【问题讨论】:

  • 有一个简单的解决方案,但在我开始之前:您是否有任何理由不只是从一开始就将其存储为数字?
  • 检查this answer 然后只需附加一个allMatch 来检查它们是否是数字。
  • 原因 - 技术任务

标签: java arrays


【解决方案1】:

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

循环遍历你的数组:

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

【讨论】:

    【解决方案2】:

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

    类似这样的:

    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;
    }
    

    【讨论】:

    • 好的,但这缺少您遍历多维数组的部分。
    • 循环遍历数组
    • 那不行,遍历数组会给你数组。然后您需要先将其展平(或进行嵌套循环以检查您的函数是否始终返回 true),这与您的答案完全不同。这就是缺少的东西,它是问题的重要部分。
    猜你喜欢
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多