我试图动态增加二维数组的大小。但是,我收到了Array out of Bounds
错误。下面发布了代码。在这种情况下,我尝试在某些条件下动态地将值添加到二维向量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);
}
}
}
}
}
答案 0 :(得分:2)
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