Java 堆栈程序的运行时错误

Java 堆栈程序的运行时错误,java,stack,Java,Stack,我正在尝试编写一个程序,该程序将利用堆栈来检查 左括号/括号在用户输入中有其重合的右括号/括号。虽然我已经尽力搜索了代码,但似乎找不到我做错了什么。下面的代码块是我试图实现的“检查”方法 import java.util.Stack; public class Matching { public static int checking(String s) { Stack<String> stack = new Stack<>(); for (int

我正在尝试编写一个程序,该程序将利用堆栈来检查 左括号/括号在用户输入中有其重合的右括号/括号。虽然我已经尽力搜索了代码,但似乎找不到我做错了什么。下面的代码块是我试图实现的“检查”方法

import java.util.Stack;
public class Matching {

public static int checking(String s) {

    Stack<String> stack = new Stack<>();

    for (int i = 0; i < s.length(); i++) {
        if (s.substring(i, i + 1).equals("{") || s.substring(i, i + 1).equals("}")){ //if substring is a bracket

            if (s.substring(i, i + 1).equals("{"))  //if is left bracket push onto stack
                stack.push("{");

            else if (!stack.peek().equals("{") || stack.size() <= 0) //otherwise, check if left bracket is not at top or if stack is empty
                return 3; // "right brace does not have its matching left brace"

            else if (s.substring(i, i + 1).equals("}") && stack.peek().equals("{"))//otherwise if substring is a right brace and the top is a left brace
                stack.pop(); //remove from top, continue searching
        }

        if (s.substring(i, i + 1).equals("{") || s.substring(i, i + 1).equals("}")){ //if substring is a parenthesis

            if (s.substring(i, i + 1).equals("(")) // if is left parenthesis push onto stack
                stack.push("(");

            else if (!stack.peek().equals("(") || stack.size() <= 0) //otherwise, check if left parenthesis is not at top or if stack is empty
                return 1;

            else if (s.substring(i).equals(")") && stack.peek().equals("(")) //otherwise if substring is a right parenthesis and the top is a left parenthesis
                stack.pop(); //remove from top, continue searching
        }

        if (stack.size() == 0) //
            return 0;
        else if (stack.size() != 0 && stack.peek().equals("("))
            return 2;
        else if (stack.size() != 0 && stack.peek().equals("{"))
            return 4;
    }
    return 150; //checks for error
  }
 }
}


如有任何帮助或一般指示,将不胜感激

看看你的第二个
if
语句:

if (s.substring(i, i + 1).equals("{") || s.substring(i, i + 1).equals("}")){ //if substring is a parenthesis

注释说它正在检查左括号和右括号,但代码说…

@OusmaneMahyDiaw程序应该识别括号/括号是否没有右括号/括号。然而,如果用户输入类似“()”的内容,程序会输出所有内容都匹配,尽管事实上每个右括号都没有左括号。啊,ffs。谢谢你抓住了!
if (s.substring(i, i + 1).equals("{") || s.substring(i, i + 1).equals("}")){ //if substring is a parenthesis