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 楼答案
要在不运行两次的情况下测试方法,请使用
else
块:这可以使用
try-with-resources
和三元bool ? trueValue : falseValue
进行简化您还可以简化其他代码: