繁体   English   中英

如何检查2D数组中的所有行是否具有相同的大小

[英]How to check if all the lines in an 2D Array have the same size

所以我有我喜欢的2D Char数组,里面有这样的东西:

WWWSWWWW\n
WWW_WWJW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n

我需要编写一个异常,当读取它时,它检查所有行是否具有相同的长度,如果不是,则返回自定义异常。

这是我现在拥有的一些东西

for (int i = 0; i < contalinhas; i++) {
        for (int j = 0; j < linelenght; j++) {
            System.out.print(linhaslidas[i].charAt(j));
            storelab[i][j] = linhaslidas[i].charAt(j);
            String linha = linhaslidas[i].get
            //builder.append(storelab[i][j]);
            //builder.toString();
            //System.out.print(builder);

            if (storelab[i][j] != ('S') && storelab[i][j] !=  ('W') && storelab[i][j] !=  ('_') && storelab[i][j] !=  ('E')) {
                throw new MazeFileWrongChar(i,j);

正如你所看到的,我已经有一个“If”作为另一个例外(基本上,限制允许的字符类型),所以我想做一些类似的东西通过数组并计算每个的长度线。 如果它检测到至少一个大小差异,则会发生异常。

问题是,我不知道如何编码,因为我使用的是数组而不是字符串(不同的方法)。

有帮助吗?

您可以遍历数组的第一个索引并比较数组的大小:

int initialLen = storelab[0].length;

// Iterate from index 1, as we already got 0
for (int i = 1; i < contalinhas; i++) {
    int currLen = storelab[i].length;
    if (initialLen != currLen) {
        throw new SomeException();
    }
}

编辑:
如果您使用的是Java 8,则可以使用流来获得更优雅的解决方案,尽管效率较低:

long lenths = Arrays.stream(storelab).mapToInt(s -> s.length).distinct().count();
if (lengths != 1L) {
    throw new SomeException();
}

您可以使用以下示例:

public class ExampleStrings {

    public static void main(String[] args) {
        String[] valid = {"aaa", "bbb", "ccc"};
        String[] invalid = {"aaa", "bbb", "1ccc"};

        // will pass with no exception
        allTheSameLength(valid);

        // will throw an exception with appropriate message
        allTheSameLength(invalid);
    }

    private static void allTheSameLength(String[] arr) {
        if (arr == null || arr.length == 0) {
            return; // or false - depends on your business logic
        }

        // get length of first element
        // it is safe to do because we have previously checked
        // length of the array
        int firstSize = arr[0].length();

        // we start iteration from 'second' element
        // because we used 'first' as initial
        for (int i = 1; i < arr.length; i++) {
            if (arr[i].length() != firstSize) {
                throw new IllegalArgumentException("String array elements have different sizes"); // or throw exception
            }
        }

    }

}

传递null或空参数是安全的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM