Java 堆栈与 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20595624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:00:48  来源:igfitidea点击:

Java Stacks With ArrayList

javaarrayliststack

提问by SomeSickJoke

Hey guys ive come stuck once again, I can manage to push items onto a stack and pop them off. I even got working a stack with open and close brackets. But when I come to do it with ()or {}or []brackets with my code I created it seems to ignore the if statement and goes to else any ideas why.

嘿伙计们,我再次卡住了,我可以设法将项目推入堆栈并将其弹出。我什至开始使用带有开括号和闭括号的堆栈。但是,当我带着做(){}[]我的代码括号我创造它似乎忽略if语句,去到别的任何想法,为什么。

Main.java

主程序

public class DifferentBrackets {

    public static void main(String[] args) {
        Stack brackets = new Stack();
        Scanner k = new Scanner(System.in);
        System.out.println("* to Terminate or Enter bracket : ");
        String tempBrack = k.next();
        while (!tempBrack.equals("*")) {
            System.out.println("* to Terminate or Enter bracket : ");

            switch (tempBrack) {
                case "(":
                    brackets.push("(");
                    System.out.println(tempBrack + " is added");
                    break;

                case "{":
                    brackets.push("{");
                    System.out.println(tempBrack + " is added");
                    break;

                case "[":
                    brackets.push("[");
                    System.out.println(tempBrack + " is added");
                    break;

                case ")":

                    if (tempBrack.equals(brackets.arrayTop()))
                            {
                            System.out.println(brackets.pop() + " is popped");
                            }
                    else if(tempBrack.equals(brackets.arrayTop()))
                    {
                        System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
                    }
                    else 
                    {
                        System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
                    }
                    break;

//            case "}":
//                    if (tempBrack.equals(brackets.arrayTop()))
//                            {
//                            System.out.println(brackets.pop() + " is popped");
//                            }
//                    else if (!tempBrack.equals(brackets.arrayTop()))
//                    {
//                        System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
//                    }
//
//                    break;

//                case "]":
//                    if (tempBrack.equals(brackets.arrayTop()))
//                            {
//                       if (!tempBrack.equals(brackets.arrayTop()))
//                    {
//                        System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
//                    }
//                    break;
            }

            System.out.println("* to Terminate or Enter bracket : ");
            tempBrack = k.next();
        }

    }
}

Heres my Stack.java

这是我的 Stack.java

import java.util.ArrayList;

public class Stack
{
    private ArrayList<String> a;

    public Stack()
    {
       a = new ArrayList(10);       //initial capacity of 10
    }

    public boolean isEmpty()
    {
         return a.isEmpty();
    }

    public String pop()          //pop integer element
    {
        String last;
        last = a.remove((a.size()- 1));
        return(last);      //underflow will crash
    }

    public void push(String x)      //push integer element
    {
        a.add(x);
    }

    public String arrayTop()
    {
        return(a.get(a.size() -1));
    }
}

采纳答案by Alexis C.

When you add a ")"you want to check if the top of the stack contains a "(", not a ")". But this is what you actually test here.

当您添加 a 时,")"您想检查堆栈顶部是否包含 a "(",而不是 a ")"。但这就是您在这里实际测试的内容。

if (tempBrack.equals(brackets.arrayTop()))

is the same as (let's say your stack contains just "("and you entered ")") :

与(假设您的堆栈只包含"("您输入的")")相同:

if (")".equals("("))

which is obviously false.

这显然是错误的。

You have to make the check in a way that when you're in a closing parenthesis/bracket, you have to check if the top of the stack contains an openingone.

你必须做的方式,当你在一个右括号/支架的时候,你必须检查堆栈的顶部包含一个检查之一。

case ")":

    if ("(".equals(brackets.arrayTop())){
        System.out.println(brackets.pop() + " is popped");
    }
    else {
        System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
    }
    break;

The same logic applies for "{"and "[".

同样的逻辑适用于"{""["

Note that :

注意 :

  1. The API already provides a Stackclass, no need to reinvent the wheel, you should use this one.
  2. Consider using a Stack of Characters, not Strings
  3. You may end your program if a closing bracket doesn't match a top open one.
  1. API 已经提供了一个Stack类,不需要重新发明轮子,你应该使用这个。
  2. 考虑使用 Stack of Characters,而不是Strings
  3. 如果右括号与顶部开括号不匹配,您可以结束程序。

回答by robbmj

Please see the comments for an explanation. To the OP, please read and understand ZouZou's answer.

请参阅评论以获取解释。对于OP,请阅读并理解邹走的回答。

import java.util.Scanner;

public class DifferentBrackets {

    public static void main(String[] args) {
        Stack brackets = new Stack();
        Scanner k = new Scanner(System.in);
        System.out.println("* to Terminate or Enter bracket : ");
        String tempBrack = k.next();

        while (!tempBrack.equals("*")) {

            // if the user added an opening bracket
            // push it on the stack
            if (isOpeningBracket(tempBrack)) {
                brackets.push(tempBrack);
            }
            else if (isClosingBracket(tempBrack)) {
                // first check to see of the element at the 
                // top of the stack is the mirror of the closing bracket
                if (brackets.arrayTop().equals(mirror(tempBrack))) {
                    // if it is pop it from the stack
                    System.out.println(brackets.pop() + " is popped");
                }
                else {
                    System.out.println("Closed Bracket Doesnt Match Top Open Bracket");
                }
            }
            else {
                System.out.println(tempBrack + " is an unsuported character");
            }
            tempBrack = k.next();
        }
        // if there is nothing on the stack after the user enters "*"
        // the user has entered balanced brackets  
        if (brackets.isEmpty()) {
            System.out.println("Congrats your brackets are balanced");
        }
        else {
            System.out.println("Sorry your brackets are not balanced");
        }
        k.close();
    }

    // find the closing bracket's mirror
    public static String mirror(String str) {
        switch (str) {
        case ")":
            return "(";
        case "]":
            return "[";
        case "}":
            return "{";
        default:
            return null;
        }
    }

    public static boolean isOpeningBracket(String str) {
        return str.equals("(") || str.equals("{") || str.equals("[");
    }

    public static boolean isClosingBracket(String str) {
        return str.equals(")") || str.equals("}") || str.equals("]");
    }
}