所以我已经按照其他人的说法修改了我的代码(在实际查看了这个问题的算法之后),我的解决方案现在正在运行!但是我现在必须打印出错误消息。如果说你有输入,我已经完成了错误消息:“{ } < )”它将返回 ) 不匹配 < 但我还必须通知左括号保持未闭合并且右括号没有相应的左括号。我不确定如何使用我当前的实现来做到这一点。任何帮助都会很棒!谢谢,凯尔。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Stack; //using java's default stack in this case as it has more extraneous error checking
public class Question3 {
private static final String OPEN = "([{<";
private static final String CLOSED = ")]}>";
public static void main(String[] args) throws IOException {
BufferedReader inKb = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter a test string:");
String input = inKb.readLine().replaceAll(" ", "");
System.out.print(parChecker(input));
// System.out.println(successful);
}
private static boolean isOpen(char ch) {
return OPEN.indexOf(ch) >= 0;
}
private static boolean isClosed(char ch) {
return CLOSED.indexOf(ch) >= 0;
}
private static boolean matches(char open, char close) {
int openIndex = OPEN.indexOf(open);
int closeIndex = CLOSED.indexOf(close);
return (openIndex == closeIndex);
}
public static boolean parChecker(String input) {
boolean balanced = true; // is stack balanced (matching parentheses)
boolean ret = false; // return value
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length() && balanced; i++) { // if it's not
// balanced stop
// searching
char bracket = input.charAt(i);
if (isOpen(bracket)) {
stack.push(bracket);
} else if (stack.isEmpty())
balanced = false;
else {
char top = stack.pop();
if (matches(top, bracket) == false) {
System.out.println("Error: '" + bracket
+ "' does not match with '" + top + "'.");
balanced = false;
}
}
}
if (balanced && stack.isEmpty()) {
System.out
.println("The string is correct! There are no mismatched brackets");
ret = true;
} else
ret = false;
return ret;
}
}