我的问题是,名为myMarks[];
的数组获得通过整数myMarks[increase]
设置的放置(increase
)值,并且要设置的数字是用户输入的myMark
。
int increase = 0; //initializing var
int myMarks[];
private void ConfirmButtActionPerformed(ActionEvent evt) {
// setting the size of the array to never end (first loop is 0+1 then 1+1, etc.)
int myMarks[] = new int[increase + 1];
// showing the size of the array
System.out.println("Array length: " + myMarks.length);
// getting inputted mark
int myMark = Integer.parseInt(Mark.getText());
myMarks[increase] = myMark;
// checking value of increase each loop
System.out.println("Position: " + increase);
// so i can show the mathematically incorrect to user
int forCosmetic = increase + 1;
// sets next line of MarkShow to the new array value
MarkShow.append("Mark " + forCosmetic + ", " + myMarks[increase] + "\n");
// showing value of myMarks
System.out.println(myMarks[increase]);
//Updating each loop
increase++;
}
这是在JFrame中。
例如,如果用户通过变量myMark为数组输入了50,它将首先在数组中显示为:50。问题是当我们以相同的值继续循环时,数组myMarks现在是: 0、50。如果再次循环,则为0、0、50,依此类推。
我认为您尝试做的是更改数组的大小,但操作不正确。如果我误解了您的问题,请添加评论/问题。
要复制更改现有阵列,必须首先分配一个新的临时副本。然后,您必须将旧数组的所有元素复制到新数组中(浅副本几乎总是可以的)。然后,您必须将新的临时副本分配给旧阵列。
((如Viswa所言,在此处使用List<Integer>
可能会更好。但是,如果必须手动执行此操作,则这是正确的方法。)
int increase = 0; //initializing var
int myMarks[];
private void ConfirmButtActionPerformed(java.awt.event.ActionEvent evt) {
//setting the size of the NEW array to never end (first loop is 0+1 then 1+1, etc.)
int temp[] = new int[1+increase];
// IMPORTANT: must copy old array values
System.arraycopy( myMarks, 0, temp, 0, myMarks.length );
// now assign the temp copy so it replaces the original
myMarks = temp;
int myMark = Integer.parseInt(Mark.getText()); //getting inputted mark
myMarks[increase] = myMark;
int forCosmetic = increase + 1;
// ... other code...
//Updating each loop
increase++;
}