gpt4 book ai didi

java - java中无法动态增加数组的大小

转载 作者:行者123 更新时间:2023-12-02 04:57:03 26 4
gpt4 key购买 nike

我正在尝试动态增加二维数组的大小。但是,我收到一个 Array out of Bounds 错误。下面贴出代码。在这种情况下,我尝试在某种条件下动态地将值添加到二维 vector weight[][] 。任何建议都会非常有帮助!

class perceptron {
public static void main(String[] args) {
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [] classlabels = {1,1,-1,-1};
int [] [] weight = {{0,0}};
int base=0;
int i,j;
int activation=0;

for(i=0;i<myPoints.length;i++) {
for(j=0;j<classlabels.length;j++) {

activation = activation+((myPoints[i][0]*weight[i][0])+(myPoints[i]
[1]*weight[i][1]));

System.out.println("dot product of two vectors" + activation);
if((activation*classlabels[j]) <= 0) {
System.out.println("hi");

weight[i+1][0] = weight[i][0]+ (classlabels[j]*myPoints[i]
[0]);
weight [i+1][1] =weight[i][1]+(classlabels[j]*myPoints[i]
[1]);

System.out.println(weight[i+1][0]);
System.out.println(weight[i+1][1]);

base = base+classlabels[j];
System.out.println(base);
}
}
}
}
}

最佳答案

Java 数组的大小是严格固定的。您必须使用 ArrayList。

示例:

ArrayList<ArrayList<Double>> weights = new ArrayList<>();
weights.add(new ArrayList<Double>()); // extend to be 1x0
weights.get(0).add(1.2); //weights[0][0]=1.2
weights.get(0).add(2.3); // weights[0][1]=2.3

关于java - java中无法动态增加数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28663718/

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