Java – dynamic programming arrayindexoutofboundexception
•
Java
I got this strange anomaly, I really don't understand why I tried debugging and found that an error occurred while running:
opt[i][j] = Double.POSITIVE_INFINITY;
When I = = 0 and j = = 1, but this should not happen, because in this case, opt is 9 × 6 matrix
This is my code:
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()); } }
This is the input file I am reading:
8 5 2 5 2.2 3 5 6.5 5 5 3 1.8
under these circumstances:
timeSlot = 8 maxCap = 5 currentCap = 2 desCap = 5
The second line shows the price for each period Eight in total
Thank you for any help
Solution
You are using maxcap and timeslot to create arrays, and their default value is still 0 read@R_301_1373 @If not, how do you know the size of the array?
Create an array after reading maxcap and timeslot
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码