有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的代码不管输入如何都返回false?

我正在编写一个代码,该代码将从文本文件导入一个字符串,使用堆栈分析该字符串,并根据该字符串是否符合某些规则来确定该字符串属于哪种“语言”。下面的代码测试输入是否遵循模式A^nB^n(其中n大于或等于0)

public static boolean checkL2(File file) throws IOException {
    Stack l2Stack = new Stack();
    boolean bStart = false;
    char w;

    Scanner sc = new Scanner(file).useDelimiter("\\s*");

    while(sc.hasNext()) { //Load input from file onto stack
        w = sc.next().charAt(0);
        if (w == 'A') {
            if (bStart == true) {
                return false;
            } else {
                l2Stack.push('A');
            }
        }
        if (w == 'B') {
            bStart = true;
            if (l2Stack.isEmpty() == true) {
                return false;
            } else {
                System.out.print(l2Stack.pop());
            }
        }
    }
    sc.close();
    if (l2Stack.isEmpty() == true) {
        return true;
    } else {
        return false;
    }
}

我正在测试的输入是AAABBB,这符合规则,但我的方法返回false。在调试过程中,我还注意到它正在迭代两次(System.out.print(l2Stack.pop());打印6a,而不是3)。我想尝试打印堆栈的剩余内容(我认为它可能因为某种原因不是空的),但不知道怎么做

更新:这是用于打印字符串是否属于此语言的决定的代码。我想知道这是不是问题所在

PrintWriter pw = new PrintWriter(outFile);
if(checkL2(file)==true) {
    pw.print("This string fits the rules of Language 2");
}
if(checkL2(file)==false) {
    pw.print("This string does not fit the rules of Language 2");
}
pw.close();

共 (1) 个答案

  1. # 1 楼答案

    要在不运行两次的情况下测试方法,请使用else块:

    PrintWriter pw = new PrintWriter(outFile);
    if(checkL2(file)) {
        pw.print("This string fits the rules of Language 2");
    } else {
        pw.print("This string does not fit the rules of Language 2");
    }
    pw.close();
    

    这可以使用try-with-resources和三元bool ? trueValue : falseValue进行简化

    try (PrintWriter pw = new PrintWriter(outFile)) {
        pw.print(
          checkL2(file)
            ? "This string fits the rules of Language 2"
            : "This string does not fit the rules of Language 2"
        );
    }
    

    您还可以简化其他代码:

    public static boolean checkL2(File file) throws IOException {
        Stack l2Stack = new Stack();
        try (Scanner sc = new Scanner(file).useDelimiter("\\s*")) {
            boolean bStart = false;
            while(sc.hasNext()) { //Load input from file onto stack
                char w = sc.next().charAt(0);
                if (w == 'A') {
                    if (bStart) {
                        return false;
                    } else {
                        l2Stack.push('A');
                    }
                } else if (w == 'B') {
                    bStart = true;
                    if (l2Stack.isEmpty()) {
                        return false;
                    } else {
                        System.out.print(l2Stack.pop());
                    }
                }
            }
        }
        return l2Stack.isEmpty();
    }