agapito agapito - 3 months ago 13
Java Question

Rewrite a Java array based on the values of another array

I've been working in a little Java project but I can't figure out how to overwrite the elements of an array based on the values on another array.

Basically I have two arrays:

repeated[] = {1,4,0,0,0,3,0,0}
and
hand[] = {1,2,2,2,2,6,6,6}
. Basically I use
repeated[]
to count the amount of times a number appears on
hand[]
, and if it is between 3 and 7 it should overwrite the element with a zero but I keep getting this output
{1,0,0,2,2,6,0,6}
when it should give me
{1,0,0,0,0,0,0,0}
. What am I doing wrong?

public static void main(String[] args) {
int repeated[] = {1,4,0,0,0,3,0,0};
int hand[] = {1,2,2,2,2,6,6,6};
for(int z=0;z<repeated.length;z++){
if(repeated[z]>=3 && repeated[z]<8){
for(int f:hand){
if(hand[f]==(z+1)){
hand[f]=0;
} } } }
for(int e:hand){
System.out.print(e+",");
}
}

Answer

First, the value in repeated is offset by one (because Java arrays start at index zero). Next, you need to test if the value is >= 3 (because 6 only appears 3 times). And, you could use Arrays.toString(int[]) to print your array. Something like,

public static void main(String[] args) {
    int repeated[] = { 1, 4, 0, 0, 0, 3, 0, 0 };
    int hand[] = { 1, 2, 2, 2, 2, 6, 6, 6 };
    for (int z = 0; z < repeated.length; z++) {
        if (repeated[hand[z] - 1] >= 3) {
            hand[z] = 0;
        }
    }
    System.out.println(Arrays.toString(hand));
}

Output is

[1, 0, 0, 0, 0, 0, 0, 0]
Comments