对于空数组,Codewars蜗牛测试失败

时间:2018-02-13 13:53:08

标签: java arrays

这是kata:https://www.codewars.com/kata/snail/train/java

我想出了这段代码。

import java.util.ArrayList;
import java.util.Arrays;
public class Snail {


public static int[] snail(int[][] array) {
ArrayList<Integer> snailArrayList = new ArrayList<>();
    int direction = 3;
    int x = 0;
    int y = 0;

    if (array.length != 0) {
        while (snailArrayList.size() < array.length * array.length) {
            if (direction == 3) {
                while (y <= array.length - 1 && array[x][y] != -1) {
                    snailArrayList.add(array[x][y]);
                    array[x][y] = -1;
                    y++;
                }
                y--;
                x++;
                direction = 6;
            } else if (direction == 6) {
                while (x <= array.length - 1 && array[x][y] != -1) {
                    snailArrayList.add(array[x][y]);
                    array[x][y] = -1;
                    x++;
                }
                x--;
                y--;
                direction = 9;
            } else if (direction == 9) {
                while (y >= 0 && array[x][y] != -1) {
                    snailArrayList.add(array[x][y]);
                    array[x][y] = -1;
                    y--;
                }
                y++;
                x--;
                direction = 12;
            } else if (direction == 12) {
                while (x > 0 && array[x][y] != -1) {
                    snailArrayList.add(array[x][y]);
                    array[x][y] = -1;
                    x--;
                }
                x++;
                y++;
                direction = 3;
            }
        }
    }
    int[] snailArray = new int[snailArrayList.size()];
    if (snailArray.length != 0) {
        for (int i = 0; i < snailArrayList.size(); i++) {
            snailArray[i] = snailArrayList.get(i);
        }
    }
    return snailArray;
} 
}

它在我的手机上工作正常,但由于某种原因,当给出一个空数组时它无法通过测试。我得到的错误是:

[[]] should be sorted to []. 

java.lang.ArrayIndexOutOfBoundsException: 0
at Snail.snail(Snail.java:15)
at SnailTest.test(SnailTest.java:35)
at SnailTest.SnailTest2Empty(SnailTest.java:62)

令我感到困惑的是,如果使用空数组,程序甚至无法输入if(array.length != 0)语句。我确信解决方案很简单,但我无法看到它。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:-1)

if (array[0].Length == 0)
    {
        return new int[0];
    }