EmptyStackException错误

时间:2014-04-16 23:35:33

标签: java stack

所以我试图用教授提供给我的驱动程序文件做一个BalancedSymbols类。我在某些情况下让它工作,但在其他情况下我得到EmptyStackException错误。

以下是提示:

The BalancedSymbols class is a utility class that will be used to check if parentheses     (), brackets [], and braces {} are matched in a given string. The BalancedSymbols class object will never be instantiated. It has the following method:

public static String balancedSymbols(String lineToCheck)

The balancedSymbols method's argument is a string that can contain parenthesis, brackets, and braces. Other characters or numbers can appear before/after/between them.

If all symbols ({([) matched, then the method should return the string:

"Everything is matched!"

If there is a closing parenthesis, bracket, or brace that does not have its corresponding opening parenthesis, bracket, or brace,
then for the first such character, return a string with its position such as:

") at the position 15 does not match."

"] at the position 12 does not match."

OR

"} at the position 28 does not match."

The first character of the string is at position 0.

If there are no matching closing parenthesis, bracket, and/or brace when you reach the end of the string after checking each character, return a string notifying the last opening parenthesis, bracket, or brace that did not have its matching closing one as:

") is missing."

"] is missing."

OR

"} is missing."

Requirement:

You need to implement this method using a Stack from java.util package.

You can use the string "A" as a token for parentheses, "B" as a token for brackets, "C"    as a token for braces.

When an opening parenthesis is read, push the token "A", and when a closing parenthesis is read, pop the token "A" if available.
A similar operation can be done for others. Only if the stack is empty when you finish reading all characters of the string, you can confirm that everything was matched. Otherwise, the method needs to return an appropriate message stated above

以下是给我的驱动程序文件:

import java.io.*;

public class Assignment11
 {
  public static void main (String[] args) throws IOException
   {
   char input1;
   String inputInfo;
   String line = new String();

   printMenu();

   InputStreamReader isr = new InputStreamReader(System.in);
   BufferedReader stdin = new BufferedReader(isr);

   do  // will ask for user input
    {
     System.out.println("What action would you like to perform?");
     line = stdin.readLine();
     input1 = line.charAt(0);
     input1 = Character.toUpperCase(input1);

     if (line.length() == 1)
      {
       // matches one of the case statements
       switch (input1)
        {
         case 'E':   //Enter String
           System.out.print("Please enter a string.\n");
           inputInfo = stdin.readLine().trim();
           System.out.println(BalancedSymbols.balancedSymbols(inputInfo));
           break;
         case 'Q':   //Quit
           break;
         case '?':   //Display Menu
           printMenu();
           break;
         default:
           System.out.print("Unknown action\n");
           break;
        }
      }
     else
      {
       System.out.print("Unknown action\n");
      }
    } while (input1 != 'Q' || line.length() != 1);
   }


  /** The method printMenu displays the menu to a user**/
  public static void printMenu()
   {
     System.out.print("Choice\t\tAction\n" +
                    "------\t\t------\n" +
                    "E\t\tEnter String\n" +
                    "Q\t\tQuit\n" +
                    "?\t\tDisplay Help\n\n");
  }
}

以下是我编码的内容:

import java.util.Stack;
public class BalancedSymbols
{
   private static final String OPEN = "([{";
  private static final String CLOSE = ")]}";

   public static String balancedSymbols(String lineToCheck)
   {
   Stack<String> stack = new Stack<String>();
   boolean balanced = true;

   int index = 0;
   String curr = "";
   String top = "";
   char missedChar = ' ';
   while(balanced && index < lineToCheck.length())
   {
       curr = lineToCheck.substring(index, index + 1);

       if(OPEN.indexOf(curr) > -1)
       {
           stack.push(curr);

           missedChar = CLOSE.charAt(OPEN.indexOf(curr));
       }
       else if(CLOSE.indexOf(curr) > -1)
       {
           top = stack.pop();

           if(OPEN.indexOf(top) != CLOSE.indexOf(curr))
           {                      
               balanced = false;
               break;
           }

       }          

       index++;
   }  

   if(index > lineToCheck.length())
   {
       missedChar = CLOSE.charAt(OPEN.indexOf(stack.peek()));
   }

   if(balanced && stack.isEmpty())
   {
       return "Everything is matched!";
   }
   else if(index < lineToCheck.length())
   {
       return missedChar + " at the position " + index + " does not match.";      
   }
   else
   {
       return missedChar + " is missing.";
   }
   }

}

我能够在匹配时传递一些测试用例,但是当我输入类似&#34; [[[[] [] [] [] []]]]] [[]的内容时] [] [] [] []]]]&#34;我得到一个EmptyStackException错误,以及一些其他输入。

除此之外,其他输入给我错误的支架类型,比如说&#39;)&#39;&#39;缺少而不是&#39;}&#39;。

我很擅长编写堆栈,所以感谢我对代码的任何帮助。这也是我的第一个问题,所以如果它很长或很难阅读我会道歉。

1 个答案:

答案 0 :(得分:0)

以下是如何开始的提示:

  1. 不需要arraylist。您创建一个Stack对象。堆栈myStack = new Stack();

  2. 您需要使用:push,pop和peek方法

  3. 你需要一个while循环,读取字符串中的第一个字符(lineToCheck)

  4. 如果是左括号将其推入堆栈,如果当前字符是右括号,请检查最后一个是否为左括号(使用peek方法)

    如果是pop,则设置你的布尔值以退出循环并打印字符不匹配的位置。

    1. 支架

    2. 现在相同
    3. 大括号

    4. 如果到达字符串的最后一个字符并检查堆栈是否为空,则最后
    5. 。如果没有,那么缺少一个关闭的

    6. 我希望这有帮助!

相关问题