user10953393
user10953393

Reputation:

Array is being changed when in for statement

I think that it supposed to be posted with entire codes in this time.

When I'm trying to get values from Scanner into array named "score",

the second for statement shows unexpected outcomes.

import java.util.Scanner;

public class B1546 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int N = input.nextInt();
        int[] score = new int[N];
        Max scoreMax = new Max();
        double sum = 0;

        for (int i=0; i<N; i++) {
            score[i] = input.nextInt();
        }

        for (int i=0; i<N; i++) {
            System.out.println(score[i]); // this show the problems
            sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
        }

        System.out.println(sum / N);
    }
}

class Max {
    int max (int[] score) {
        int[] tmpArray;
        tmpArray = score;

        for( int i=0; i<score.length-1; i++) {
            for( int j=i+1; j<score.length; j++) {
                if (tmpArray[i]<tmpArray[j]) {
                    int tmp = tmpArray[i];
                    tmpArray[i] = tmpArray[j];
                    tmpArray[j] = tmp;
                }
            }
        }
        return tmpArray[0];
    }
}

For example, when I type 3 10 20 30 then It comes 10 20 10 ...

not 10 20 30 ...

I don't know what is the problem.

Upvotes: 1

Views: 69

Answers (3)

Kevin Cruijssen
Kevin Cruijssen

Reputation: 9326

int[] are objects and therefore are passed-by-reference in Java. When you do the following in your Max#max(int[]) method:

int[] tmpArray;
tmpArray = score;

Both tmpArray and score will hold the same reference, so when you swap values in the tmpArray, the score-array will be modified as well.

You'll have to create a new integer-array instead for the tmpArray, and copy the values. The simplest would be one of the following two:

int[] tmpArray = score.clone();

// or:

int[] tmpArray = Arrays.copyOf(score, score.length);

I would suggest the second, the .clone() is normally used for other purposes.

Try it online.

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

int max (int[] score) {
    int[] tmpArray;
    tmpArray = score;
}

score is a reference to the array object. Here you create a new reference to the existed array. To fix it, jut make a new array object:

int max(int[] score) {
    int[] tmpArray = Arrays.copyOf(score, score.length);
}

Upvotes: 0

user10762593
user10762593

Reputation:

Your Max.max method changes the array - the 3 lines starting with int tmp =.

Likely the source of your problems is not understanding reference types. tmpArray = score does not make a separate copy of the array score -- you just have two references to the same array. This concept is fundamental to Java programming.

Upvotes: 2

Related Questions