简体   繁体   English

根据另一个数组的值重写Java数组

[英]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. 我一直在一个小的Java项目中工作,但是我无法弄清楚如何根据另一个数组上的值覆盖一个数组的元素。

Basically I have two arrays: repeated[] = {1,4,0,0,0,3,0,0} and hand[] = {1,2,2,2,2,6,6,6} and 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 corresponding element in hand[] 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} . 基本上我有两个数组: repeated[] = {1,4,0,0,0,3,0,0}hand[] = {1,2,2,2,2,6,6,6}和我使用repeated[]来计算数字出现在hand[]上的次数,如果它在3到7之间,则应该用零覆盖hand[]的相应元素,但我会不断得到此输出{1,0,0,2,2,6,0,6}何时应该给我{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+",");
    }
    } 

First, the value in repeated is offset by one (because Java arrays start at index zero). 首先, repeated的值偏移一个(因为Java数组从索引零开始)。 Next, you need to test if the value is >= 3 (because 6 only appears 3 times). 接下来,您需要测试该值是否>= 3 (因为6仅出现3次)。 And, you could use Arrays.toString(int[]) to print your array. 并且,您可以使用Arrays.toString(int[])打印您的数组。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM