Noah Bender
Noah Bender

Reputation: 13

Java Previous Array Values Set to 0

My issue is that the array called myMarks[]; gets placement (myMarks[increase]) values set through the integer increase and the number to be set to is myMark which is inputted by the user.

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++;
}

This is inside of a JFrame.

For example, if you the user inputted 50 for the array through the variable myMark, it would first show up in the array as: 50. The issue is when we continue the loop with the same value, the array myMarks is now: 0, 50. If we loop again it would be 0, 0, 50 and so on.

Upvotes: 0

Views: 84

Answers (1)

markspace
markspace

Reputation: 11020

I think what you're trying to do is change the size of an array but you're not doing it correctly. Please add comments / questions if I misunderstood your question.

To copy change an existing array, you must first allocate a new temporary copy. Then you must copy all the elements of the old array into the new array (a shallow copy is almost always fine). Then you have to assign the new temporary copy to the old array.

(As Viswa commented, using List<Integer> would probably be better here. But if you must do this manually, this is the correct way to do it.)

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++;
}

Upvotes: 1

Related Questions