我正在编写一个代码,它将从文本文件中导入一串字符,使用堆栈分析字符串,并根据它是否符合某些规则来确定字符串所属的“语言”。下面的代码测试输入是否遵循模式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());
打印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();
答案 0 :(得分:2)
要在不运行两次的情况下测试方法,请使用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();
}