当从其他方法调用时,Helper Method不会工作,但是来自main

时间:2018-03-07 03:16:00

标签: java

我有一个帮助方法,我从同一个类中的另一个方法调用。当我从main测试时,它工作正常。但是一旦我在其他课堂上使用它,它根本就不起作用。我无法弄清楚出了什么问题。 这是辅助方法:

private boolean checkStack(Stack<String> stack,String check) { 
    System.out.println(stack);
    System.out.println(check);
    Stack<String> jump = new Stack<String>();
    int count = 0;
    String temp = "";
    while (!stack.empty()) {
        temp = stack.pop();
        if (check == temp) {
            count++;
        }
        jump.push(temp);
    }
    while (!jump.empty()) {
        temp = jump.pop();
        stack.push(temp);
    }
    System.out.println(count);
    if (count != 0) {
        return true;
    } else {
        return false;
    }

}

我将从主要测试它:

    pathSoFar.push("00");
    pathSoFar.push("01");
    pathSoFar.push("20");
    pathSoFar.push("23");
    System.out.println(pathSoFar);
    String checkfor = "20";
    System.out.println(test01.checkStack(pathSoFar,checkfor));

但是当我用另一种方法调用它时它不会起作用:

            for (String n : possibleSpots) {
                System.out.println();
                String check = n;
                if (!checkStack(pathSoFar, n)) {
                    pathSoFar.push(n);
                    String x = ""+n.charAt(0);
                    String y = ""+n.charAt(1);
                    int nextRow = Integer.parseInt(x);
                    int nextCol = Integer.parseInt(y);
                    System.out.println(nextRow + "" + nextCol + " = next move.");
                    if (findPath(wordToFind, pathSoFar, nextRow, nextCol)) {
                        return true;
                    }
                } else{}
            }

如果有帮助,这是方法标题:

private boolean findPath(String wordToFind, Stack<String> pathSoFar, int row, int col) {

1 个答案:

答案 0 :(得分:0)

possibleSpots 可以包含String文字或String对象。

问题出在以下一行

if (check == temp)

将其更改为

if (check.equals(temp))

字符串匹配使用==完成,它仅适用于字符串文字。 这就是为什么它在一个案例中适用于你而在另一个案例中不起作用的原因。

要了解差异,请查看以下链接:

What is the difference between == vs equals() in Java?