2011-03-11 99 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數組分配內存。