2011-03-11 104 views
3

我得到这个奇怪的例外,我真的不明白为什么..我试图调试,并发现它运行时出错:动态规划ArrayIndexOutOfBoundException

opt[i][j] = Double.POSITIVE_INFINITY; 

,当我== 0和j == 1,但这不应该发生,因为在这种情况下,opt是一个9x6矩阵。

这是我的代码:

public class Versie3 { 

    private int desCap; 
    private int currentCap; 
    private int maxCap; 
    private int timeSlot; 
    private static ArrayList<Double> prices; 
    private double[][] opt = new double[timeSlot + 1][maxCap + 1]; 

    public Versie3() throws FileNotFoundException { 

    } 

    public void readInput(String s) throws FileNotFoundException 
    { 
     FileReader fr = new FileReader(s); 
     Scanner sc = new Scanner(fr); 

     timeSlot = sc.nextInt(); 
     maxCap = sc.nextInt(); 
     currentCap = sc.nextInt(); 
     desCap = sc.nextInt(); 
     prices = new ArrayList<Double>(timeSlot); 

     while (sc.hasNextDouble()) { 
      prices.add(sc.nextDouble()); 

     } 
    } 

    public double calculateOptimal() 
    { 
     for (int i = 0; i <= timeSlot; i++) 
     { 
      for (int j = 0; j <= maxCap; j++) 
      { 
       if (i == 0) 
       { 
        if (j != desCap) 
        { 

         opt[i][j] = Double.POSITIVE_INFINITY; // <--here it goes Wrong! 
        } 
        else 
        { 
         opt[i][j] = 0; 
        } 
       } 
       else if (j == 0) 
       { 
        opt[i][j] = Math.min(opt[i - 1][j], 
          opt[i - 1][j + 1] 
            - prices.get(i-1)); 
       } 
       else if (j == maxCap) 
       { 
        opt[i][j] = Math.min(opt[i - 1][j], 
          opt[i - 1][j - 1] 
            + prices.get(i-1)); 
       } 
       else 
       { 
        opt[i][j] = Math.min(Math.min(opt[i - 1][j], 
        opt[i - 1][j - 1] 
        + prices.get(i - 1)),opt[i - 1][j + 1]- prices.get(i-1)); 
       } 
      } 
     } 
     return opt[timeSlot][currentCap]; 
    } 

    public static void main(String[] args) throws FileNotFoundException { 
     Versie3 v3 = new Versie3(); 
     v3.readInput("input.txt"); 
     System.out.println("prices: " + prices.toString()); 
     System.out.println("timeSlot: " + v3.timeSlot); 
     System.out.println("maxCap: " + v3.maxCap); 
     System.out.println("currentCap: " + v3.currentCap); 
     System.out.println("desCap: " + v3.desCap); 
     //System.out.println("minimum cost: "+v3.calculateOptimal()); 
     System.out.println(v3.prices.size()); 

    } 

} 

这是输入文件我读:

8 5 2 5 
2.2 3 5 6.5 5 5 3 1.8 

在这种情况下:

timeSlot = 8 
maxCap = 5 
currentCap = 2 
desCap = 5 

第二行显示每个时间段的价格。所以共有8个。

我感谢所有帮助表示感谢。

+1

+1了所有必要的信息结构完善的问题。 –

回答

2

您正在使用maxCaptimeSlot创建阵列,但它们仍具有默认值0readInput()没有被调用,因此还怎么能知道要什么尺寸的阵列?

创建数组你maxCaptimeSlot读取之后。

1

你确定是什么的Maxcap等于之前,您初始化您的选择阵列。

3

opt是越来越timeSlotmaxcap设置前的施工时间intialized。

所以你创建一个数组

private double[][] opt = new double[0 + 1][0 + 1]; 

你必须在readInput方法创建阵列的用户已经输入的值之后。

1

当你创建一个类的对象Versie3maxCaptimeSlot采取的0其默认值和阵列opt用的1 x 1大小创建。

这个你去阅读它重写的maxCaptimeSlot但数组大小值的文件后保持不变

为了解决这个问题,您已经阅读了尺寸后,在功能readFile数组分配内存。