1

I started to learn Java recently and I have a problem with the StringBuilder class. I have a StringBuilder instance and after I append many strings to it, I want to empty it to append a new sequence.

I have tried many different things like allocating a new StringBuilder for that variable, delete, setLength and all of that, but I get an exception ArrayIndexOutOfBoundsException.

Why am I getting this exception? How can I do this task effectively?

Edit: so in detail what i was trying to program caculate app like Window caculate app, the main thing is process variable will store number and operation so when it need to have a result it will cal caculate method to do that. It will work exactly like window caculate app. It works fine if i continue to do "+" operation repeatly, it updates the result after hit operation button, but when hit "=" button it gets an exception ArrayIndexOutOfBoundsException at process variable. I knows my code is complicated, hope you guys wil find the solution and i have tried all the solution that you guys recommended, all of that ges exception

public class Cal extends javax.swing.JFrame {

/**
 * Creates new form Cal
 */



    StringBuilder process ;
    StringBuilder textOutcome ;

    boolean isResult; // it means that you just hit the operation button or "=" button

    boolean isRestart;// it means after you hit "=" button if after that you continue hit the operation button that will false ,if you hit numbe button it will true
     public double caculate ()
    {

        String[] split = process.toString().split(" ");
        double result = Double.valueOf(split[1]);
        for(int i = 2 ; i < split.length;i++)
        {
            if(split[i].equals("+"))
            {
              result += Double.valueOf(split[i + 1]);
              i += 1;
            }


        }
        return result;


    }
public Cal() {
    initComponents();
     process = new StringBuilder();
   textOutcome =  new StringBuilder();

    isResult = true;
   isRestart = false;
    GridLayout grid = new GridLayout(4,4,10,10);


    JButton btnAdd = new JButton("+");
       btnAdd.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
           //To change body of generated methods, choose Tools | Templates.
           txtOutcome.setText(String.valueOf(caculate()));
           process.append( " "+e.getActionCommand());
           txtProcess.setText(process.toString());
           isResult = true;
           isRestart = false;





        }
    });

    pGrid.add(btnAdd);
     JButton btn4 = new JButton("4");
     btn4.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(isResult)
               {
                   isResult = false;
                   textOutcome = new StringBuilder();
                   textOutcome.append( e.getActionCommand());
                   txtOutcome.setText(textOutcome.toString());
                   if(isRestart)
             {
                 process = new StringBuilder();

                   isRestart = false;
             }
                   process.append( " "+e.getActionCommand());



               }
             else
             {

                  textOutcome.append( e.getActionCommand());
                   txtOutcome.setText(textOutcome.toString());

                   process.append(e.getActionCommand());

             }

        }
    });
      pGrid.add(btn4);
      JButton btnResult = new JButton("=");
      btnResult.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             txtOutcome.setText(String.valueOf(caculate()));
          process.delete(0, process.length());

              process.append(String.valueOf(caculate()));
                txtProcess.setText(process.toString());
              isResult = true;
              isRestart = true;

        }
    });

    pGrid.add(btnResult);
      pGrid.setLayout(grid);
}

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel pGrid;
private javax.swing.JTextField txtOutcome;
private javax.swing.JTextField txtProcess;
// End of variables declaration                   

}

Tú Anh Dư
  • 135
  • 1
  • 10
  • 2
    Possible duplicate of [StringBuilder - Reset or create a new](http://stackoverflow.com/questions/18766780/stringbuilder-reset-or-create-a-new) – Jaydeep Rajput Apr 03 '17 at 18:31
  • I think this is a slightly different question b/c the user is getting an exception as opposed to wondering about the performance implications of different ways of performing the task. – WattsInABox Apr 03 '17 at 18:35

2 Answers2

0

please try creating a new empty StringBuilder

sb = new StringBuilder("");
0xDEADBEEF
  • 590
  • 1
  • 5
  • 16
0
    StringBuilder sB = new StringBuilder();
    sB.append("Aaa");
    sB.append("Bbb");
    sB.append("Ccc");
    System.out.println(sB); // prints: AaaBbbCcc

    sB.delete(0, sB.length());
    sB.append("Ddd");
    System.out.println(sB); //prints: Ddd
Pardeep
  • 945
  • 10
  • 18