Java 为什么我的代码不管输入如何都返回false?
我正在编写一个代码,该代码将从文本文件导入一个字符串,使用堆栈分析该字符串,并根据该字符串是否符合某些规则来确定该字符串属于哪种“语言”。下面的代码测试输入是否遵循模式A^nB^n(其中n大于或等于0) 我正在测试的输入是Java 为什么我的代码不管输入如何都返回false?,java,Java,我正在编写一个代码,该代码将从文本文件导入一个字符串,使用堆栈分析该字符串,并根据该字符串是否符合某些规则来确定该字符串属于哪种“语言”。下面的代码测试输入是否遵循模式A^nB^n(其中n大于或等于0) 我正在测试的输入是AAABBB,它符合规则,但我的方法返回false。在调试过程中,我还注意到它重复了两次(System.out.print(l2Stack.pop());prints 6个A,而不是3个)。我想尝试打印堆栈的剩余内容(我认为它可能因为某种原因不是空的),但不知道怎么做 更新:这
AAABBB
,它符合规则,但我的方法返回false。在调试过程中,我还注意到它重复了两次(System.out.print(l2Stack.pop());
prints 6个A,而不是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();
要在不运行两次的情况下测试方法,请使用
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();
}
顺便说一句,您可以编写
返回l2Stack.isEmpty()
而不是if(l2Stack.isEmpty()==true){return true;}else{return false;}
(最后一行)。@pzaenger很有趣,我这么说。他们似乎没有在听。顺便说一句,您不必检查布尔值的真值(例如l2Stack.isEmpty()==true
)。只需检查布尔值本身(l2Stack.isEmpty()
)。另外,如果条件为true时返回true,如果条件为false时返回false,则可以只返回条件。因此,您的最终if构造可以简单地重写为return l2Stack.isEmpty()代码>。8行缩减为一行:),您可以将扫描仪包装在“使用资源进行尝试”块中,而不是自己手动关闭。因此,您知道您正在运行两次方法,对吗?因此,它将打印所有内容两次,并读取文件两次,等等?如果需要,请使用else而不是第二次
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();
}