线程“main”中的异常java.lang.IndexOutOfBoundsException:索引:1,大小:0

时间:2013-11-10 22:39:27

标签: arrays list indexing bounds out

我不确定为什么我一直收到此错误消息。我正在尝试将int添加到结果中。我不明白为什么它不让我这样做,当我尝试将三个放入索引size1-1时,似乎结果将是空的。

错误信息:(标记了第452,423,11行)

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.set(Unknown Source)
at BigInt.singleDigitMultiply(BigInt.java:452)
at BigInt.multiply(BigInt.java:423)
at Dem.main(Dem.java:11)

BigInt类的部分:

 public BigInt multiply(BigInt B2) {
BigInt result = new BigInt();
BigInt B1 = this;   
result = singleDigitMultiply(B1,B2); Line 423
    return result;

}

private BigInt singleDigitMultiply(BigInt B1, BigInt B2) {
    int size1 = B1.num.size(), size2 = B2.num.size();
    BigInt result = new BigInt();
    //result.num = new ArrayList (Collections.nCopies( size1+1, null ));
    boolean carryover = false;
    int one, two, three, four, five, carry;
    for (int i = size1-1; i >= 0; i--) {

         one = B1.num.get(i);
         two = B2.num.get(0); 

         int prod = B1.num.get(i) * B2.num.get(0);
         int prodInt = prod / 10;
         if (prod > 9) carryover = true;

         if (i == size1-1) {

         if (carryover) {
         three = prod % (prodInt * 10); 
         }
         else {
            three = prod;
         }

    System.out.println( result.num.set(size1-1,three));          Line 452
         }

    //   else {
        //   four = B1.num.get(i+1) * two;
    //       carry = four % (four - prodInt);
    //       if (four > 9) {
    //   
    //       five = prod + carry;
    //       three = five % (prodInt * 10);
    //       }
    //       else {
    //           three = prod;
    //       }
        //   result.num.add(i,three);
    //   }




    }

    return result;
}

主要课程:

public class Dem {
public static void main(String[] args) {
BigInt B1 = new BigInt("55");
BigInt B2 = new BigInt("1");
BigInt D = new BigInt();
int u = 8;
int j = 10;

//BigInt J = new BigInt("u");
D = B1.multiply(B2);           Line 11
System.out.println(u/j);
}
}

1 个答案:

答案 0 :(得分:0)

问题是您可能尚未在尝试访问此值时设置result.num,因此您应该在singleDigitMultiply(...)方法中的任何位置分配它或者在BigInt构造函数中,但在读取值之前。