【问题标题】:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:1,大小:0
【发布时间】:2013-11-22 15:42:16
【问题描述】:

我不太确定为什么我不断收到此错误消息。我正在尝试将 int 3 添加到结果中。我不明白为什么它不允许我这样做,当我尝试将三个放入索引 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);
}
}

【问题讨论】:

    标签: arrays list indexing bounds out


    【解决方案1】:

    问题是你可能还没有在你试图访问这个值的时候设置result.num,所以你应该在任何时候分配它,无论是在singleDigitMultiply(...)方法还是@987654323 @构造函数,但在读取值之前。

    【讨论】:

    • 我不确定我明白你在说什么...设置 result.num?在获得正确值之前,如何设置我想要的值?
    • 我的意思是这段代码行不通,因为result.num从不接收值,所以你会在result.num.set(...)中得到一个空指针异常,但是我猜这只是你没有包含它或忘记添加它。
    • 怎么没有收到值?我正在尝试将 int 3 设置为索引 size1-1。我有另一种方法可以正常工作。谢谢。
    • 实际上,我建议您检查您的代码,因为它有点令人困惑。例如,public BigInt multiply(BigInt B2) 在 BigInt 类中没有意义。 BigInt 类中的private BigInt singleDigitMultiply(BigInt B1, BigInt B2) 也是如此。我会创建一个Operation 类来包含这些方法,因为从语义的角度来看这是没有意义的,所以很难理解。
    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2018-10-29
    • 2017-01-02
    • 2016-12-28
    相关资源
    最近更新 更多