无法将字符串作为String数组返回

时间:2018-04-11 18:48:16

标签: java arrays arraylist methods return-type

我正在为hackerrank问题编写一个解决方案,Encircular并编写了一个完整的解决方案,但是我得到一个错误,因为我需要在一个字符串数组的方法上返回一个字符串,我似乎无法想象如何我可以修好它。我在网上搜索并尝试了一些不同的东西,但没有运气。我在下面粘贴了我的代码;

public class Encircular {
    static String[] find(String[] commands) {
        int x = 0;
        int y = 0;
        boolean goUp = false;
        for (int i = 0; i < commands.length(); i++) {
            switch (commands.charAt(i)) {
                case 'G' :
                    if (goUp) {
                        y++;
                    } else {
                        x++;
                    }
                    break;
                case 'L' :
                    goUp = true;
                    break;
                case 'R' :
                    goUp = false;
                    break;
            }
        }
        if (x == 0 && y == 0) {
            return "YES";
        }
        return "NO";

    }

    public static void main(String[] args) {
        System.out.println(doesCircleExist("GLGLG"));
        System.out.println(doesCircleExist("GRGL"));
    }

我得到的错误是:

      location: variable commands of type String[]
Solution.java:37: error: incompatible types: String cannot be converted to String[]
            return "YES";
                   ^
Solution.java:39: error: incompatible types: String cannot be converted to String[]
        return "NO";

我尝试将字符串存储为数组,然后像这样返回数组,但没有运气;

ArrayList<String> list = new ArrayList<String>();
list.add("YES");
list.add("NO");


 if (x == 0 && y == 0) {
        return list.get[0];
    }
    return list.get[1];

此外,我收到此错误,我不确定它的含义:

/usr/lib/jvm/java-8-sun/bin/javac -encoding UTF-8  -classpath ':*:/usr/share/java/*' Solution.java 1> compile.err 2>&1

1 个答案:

答案 0 :(得分:2)

您将方法的返回类型作为字符串数组。如果您将其更改为

static String find(String[] commands)

然后它会让你返回一个字符串

编辑:

由于您无法更改方法减速度,因此您可以简单地执行@raluca建议的操作并创建两个不同的数组。一个只包含yes,一个只包含no并返回其中一个。