gpt4 book ai didi

java - 动态规划 ArrayIndexOutOfBoundException

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:34:05 25 4
gpt4 key购买 nike

我得到了这个奇怪的异常,我真的不明白为什么..我尝试调试并发现它在运行时出错了:

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

并且当 i == 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 个。

非常感谢您的帮助。

最佳答案

opt timeSlotmaxcap 设置之前在构建时初始化。

所以你创建了一个数组

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

用户输入值后,您必须在 readInput 方法中创建数组。

关于java - 动态规划 ArrayIndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5276554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com