ArrayList无缘无故地打印出额外的零作为第一个元素

时间:2017-11-09 20:38:47

标签: java arraylist

我的程序应该检查从用户输入输入的平衡括号。我的程序涉及GUI,但与问题无关。如果输入的括号不平衡,我还必须向用户返回额外括号的位置。我创建了一个ArrayList,显示了输入的额外括号中的位置。我测试了程序,并且ArrayList以0作为第一个元素返回,无缘无故。然后,它返回所需的答案。而且,它无缘无故地将数字分开。下面是我的代码,但是,我只包含与我的问题相关的代码:

screenshot of output

    public boolean balancedParentheses(String inputtedInfo) 
    {
        Stack<Character> stack  = new Stack<Character>();

        for(int i = 0; i < inputtedInfo.length(); i++) 
        {
            char c = inputtedInfo.charAt(i);
            if(c == '(') 
            {     
                stack.push(c);

            } 

            else if(c == ')') 
            {

                if(stack.isEmpty() || stack.pop() != '(') 
                {
                  return false;

                }


            }



        }
        return stack.isEmpty();

    }

    public String determineProblem(String inputtedInfo)
    {
      List<Integer> positions = new ArrayList<>();
      String str = "";
      int q = 0;     
      int r = 0;


      for(int s = 0; s < inputtedInfo.length(); s++)
      {
         char d = inputtedInfo.charAt(s);

         if (d == '(')
         {
            q += 1;
         }
         else if (d == ')')
         {
            r += 1;
         }
         if (q > r && d == '(')
         {
            positions.add(s);

         }
         else if (r > q && d == ')')
         { 
            positions.add(s);
         }
      }

      String positionsString = "";

      for (int o : positions)
      {
        positionsString += o + "\t";
      }

      if (q > r)
      {
          str = "There are excessive open parentheses! There are " + (q - r) + " extra open parentheses. The offending parentheses are at positions: "
          + positionsString;

      }
      else if (r > q)
      {
         str = "There are excessive closed parentheses! There are " + (r - q) + " extra closed parentheses. The offending parentheses are at positions: "
        + positionsString;
      }

      return str;


    }

    public String printResults()
    {


          String preresults = String.valueOf(balancedParentheses(inputtedInfo));
          String results = "";
          if (preresults == "true")
          {
            results = "You have balanced parentheses!";
          }
          else if (preresults == "false")
          {
            results = "You have unbalanced parentheses!";
          }


          String results2 = determineProblem(inputtedInfo);


          return results + " " + results2;

    }

1 个答案:

答案 0 :(得分:0)

在DetermProblem循环的第一次迭代中,d为'('所以q设置为1.然后你就是块

if( q > r && d == '(' ){
  positions.add(s);
}

向位置arrayList添加0。

另外:间距是因为在形成输出字符串时,每个索引之间都包含一个制表符(\ t)。