why it return to string method error in java?

631 views java

i want to output tostring() method from degree to 0 but when i=degree in for loop it does not work if i=degree-1 works i don't know why?

public String toString(){
        String q="";

    for (int i = degree; i >=0 ; i--) {
         if (i>1)
            q+=" +"+getCoefficient(i)+"x^"+i;
         else if((i<1)&&(i!=0))
             q+=" "+getCoefficient(i)+"x^"+i;

        else if(i==1&&getCoefficient(i)>0)
             q+=" +"+getCoefficient(i)+"x";
         else if(i==1&&getCoefficient(i)<0)
             q+=" "+getCoefficient(i)+"x";

         else if(i==0&&getCoefficient(i)<0)
            q+=" "+getCoefficient(0);
            q+="   +"+getCoefficient(0);

    return q;

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.get(ArrayList.java:458)
    at Polynomial.getCoefficient(Polynomial.java:46)
    at Polynomial.toString(Polynomial.java:113)
    at java.base/java.lang.String.valueOf(String.java:3042)
    at java.base/java.io.PrintStream.println(PrintStream.java:897)
    at PolynomialApplication.main(PolynomialApplication.java:32)

answered question
Add a Comment

1 Answer


There's not enough code here to be entirely sure what's going on, but a reasonable guess is that...

for (int i = degree; i >=0 ; i--) {

...should be...

for (int i = degree - 1; i >=0 ; i--) {

posted this

Please login first before posting an answer.