java – 动态编程ArrayIndexOutOfBoundException
发布时间:2020-12-15 08:38:52 所属栏目:Java 来源:网络整理
导读:我得到了这个奇怪的异常,我真的不明白为什么..我试过调试,发现运行时出错了: opt[i][j] = Double.POSITIVE_INFINITY; 当i == 0且j == 1时,但这不应该发生,因为在这种情况下,opt是9×6矩阵. 这是我的代码: public class Versie3 { private int desCap; priv
我得到了这个奇怪的异常,我真的不明白为什么..我试过调试,发现运行时出错了:
opt[i][j] = Double.POSITIVE_INFINITY; 当i == 0且j == 1时,但这不应该发生,因为在这种情况下,opt是9×6矩阵. 这是我的代码: 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个. 感谢任何帮助. 解决方法
您正在使用maxCap和timeSlot创建数组,而它们的默认值仍为0. readInput()尚未调用,那么您怎么知道制作数组的大小?
在读入maxCap和timeSlot后创建数组. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 应用Java泛型和反射导出CSV文件的方法
- java – 在Futures.transform中,使用Function和AsyncFuncti
- java – 当重写等于总是返回False时,HashMap和Hashtable的不
- Enum枚举类型
- java – 在使用它之前是否需要调用MessageDigest.reset()?
- 如何从Java ArrayList获取元素
- 两小无猜的爱恨情仇--java =+和+=揭秘
- 【SpringCloud】06.Eureka 总结
- java – 如何等待警报框在Selenium中执行操作?
- java – 无效或损坏的jarfile /usr/local/bin/selenium-ser