1

My project is supposed to do basic operations on polynomials. Each polynomial si an ArrayList of objects from class Monom. I created an interface with Swing. I made a method that transforms a String received into a Polinom object. If I use basic commands, like when I press a button, get text and show it, everything works fine. But when I call the method mentioned before (toPolinom) , the buttons do not work anymore and red lines are written in the console.

This is how the button code looks like :

 mybutton = new JButton("Suma");
    mybutton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            String pol1 = numberField1.getText();
            String pol2 = numberField2.getText();
            polinom1 = new Polinom(p1);
            polinom2 = new Polinom(p2);
            polinom1 = polinom1.toPolinom(pol1);
            polinom2 = polinom2.toPolinom(pol2);
            resultField.setText(polinom1.suma(polinom1, polinom2)
                    .toString());       

        }
    }); 

   mybutton2 = new JButton("Diferenta");
    mybutton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String pol1 = numberField1.getText();
            String pol2 = numberField2.getText();
            polinom1 = polinom1.toPolinom(pol1);
            polinom2 = polinom2.toPolinom(pol2);
            resultField.setText(rezultat.diferenta(polinom1, polinom2)
                    .toString());

        }
    });

resultField and numberField1 are type JTextField;

This is my toPolinom() method from class Polinom.java:

   public  Polinom toPolinom(String p1) {

    List<Monom> prez = new ArrayList<Monom>();
    int grad, coef;
    int i = 0;
    for(i=0; i<p1.length()-1; i=i+5){
        grad=0; coef=0;
        if(p1.charAt(i)=='+') coef=Character.getNumericValue(p1.charAt(i+1));
        else if (p1.charAt(i)=='-') coef=-Character.getNumericValue(p1.charAt(i+1));
        grad=Character.getNumericValue(p1.charAt(i+4));
        prez.add(new MonomZ(grad, coef));
    }


    return new Polinom(prez);
}

I tested this methode, and it works.

Finally, this is what I receive when I click my buttons :

   Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at tema1.Polinom.toString(Polinom.java:208)
at tema1.Fatza$1.actionPerformed(Fatza.java:61)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

The warning methode added :

  public String toString() {

    String Rezultat = "";
    for (int i = 0; i < polinom.size() - 1; i++) {
        Rezultat = Rezultat + verificare(polinom.get(i), polinom, i);
    }
    return Rezultat
            + verificare(polinom.get(polinom.size() - 1), polinom, //line 208
                    polinom.size() - 1);

}

private String verificare(Monom monom, List<Monom> polinom, int n) {
    // functia verifica daca trebuie adaugat semn sau nu
    String text;
    boolean ok = true;
    for (int i = 0; i < n; i++) {
        if (polinom.get(i).getCoef().doubleValue() != 0) {
            ok = false;
            break;
        }
    }
    double numar = monom.getCoef().doubleValue();
    if (ok == true && numar > 0) {
        text = monom.toString();
    } else {
        text = "+" + monom.toString();
    }
    if (numar < 0) {// numarul are inclus semn negativ
        text = monom.toString();
    }
    return text;
}

If I forgot any information, please ask me.

2
  • 2
    Don't ignore the exception message as it's telling you what's wrong, an ArrayIndexOutOfBoundsException, what the incorrect value is, -1 and the line number where it occurs: at tema1.Polinom.toString(Polinom.java:208). So what code is on line 208 of the Polinom class? Commented Mar 17, 2015 at 19:10
  • Please show that line of code and the code around it. Edit your question. And it matters little if it's working well anywhere else as it's not working well now. Commented Mar 17, 2015 at 19:13

3 Answers 3

3

You're calling

verificare(polinom.get(polinom.size() - 1), polinom,' 'polinom.size() - 1);

and getting an ArrayIndexOutOfBoundsException with a -1 value suggesting that your polinom collection's size is 0 when you are getting the error. Check for this, and don't call this method if the size is 0.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right. If I don't call for this methode in ActionListener, I have no errors. But How come it works in my tests and all the rest? Could you point what I am doing wrong? Thank you
@LauraD: for that you would need to create and post a minimal runnable example program or mcve.
3

in your methode:

public  Polinom toPolinom(String p1) {
    ....
    for(i=0; i<p1.length()-1; i=i+5){

you increment i every loop about 5

so imagine this string "1234567": first loop you get 12345, next loop only 67, but you try to do this:

grad=Character.getNumericValue(p1.charAt(i+4));

at this moment, i+4 = 9, and this is outOfBound... i guess (not tested it, and you don't show the line where the error is) this is your problem

2 Comments

the thing about toPolinom() is that it is made to only work for particular cases. The user must respect some rules. So my String looks like : +1X^3-2X^0.
@LauraD In this case your issue is probably from what Hovercraft mentioned as long as you are validating the length of p1. +1 anyhow as this could of been the issue had there been no rules in place to validate p1.Length%5==0
0

Everything worked perfectly after I modified the methods toString() and verificare() as follows:

      public String toString() {
    int ok = 0;
    String Rezultat = "";
    for (int i = 0; i < polinom.size(); i++) {
        Rezultat = Rezultat + verificare(polinom.get(i), polinom, i);
        if (polinom.get(i).getCoef().doubleValue() != 0)
            ok = 1;
    }
    if (ok == 1)
        return Rezultat;
    else
        return "0";

}

private String verificare(Monom monom, List<Monom> polinom, int n) {
    String text = "";

    double numar = monom.getCoef().doubleValue();
    if (n != 0 && numar > 0) {

        text = "+" + monom.toString();
    } else
        text = monom.toString();
    if (numar < 0) {// numarul are inclus semn negativ
        text = monom.toString();
    }
    return text;

}

Thank you very much for all your help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.