Java 以前的数组值设置为 0

标签 java

我的问题是名为 myMarks[]; 的数组获取通过整数 increase 设置的放置 (myMarks[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++;
}

关于Java 以前的数组值设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58751891/

相关文章:

java - 放心 - post() - java.lang.NullPointerException : Cannot invoke method trim() on null object

java - 在执行其他操作之前查找 Stream 大小

java - 模块之间的依赖管理

java - 当子类构造函数从父类(super class)扩展时,为什么它们应该覆盖父类(super class)参数化构造函数?

java - 是否可以显示多个文本字段,供用户在每个文本字段中输入他们想要的项目数?

java - 命名参数查询如何阻止 SQL 注入(inject)

java - 当Java中服务器关闭时如何重新连接客户端?

java - 带有状态代码的 Jersey Viewable

java - 词网关系

java - BuildLabel属性是如何生成的?