简体   繁体   English

我正在用Java中的“ 0”替换Evens,我在做什么错?

[英]I am trying to replaceEvens with a “0” in java, what am I doing wrong?

public static int[] replaceEvens(int[] a)  {
    int e[] = new int[a.length];
    // TODO Insert code here
    for (int i = 0; i < a.length; i++){
        if( e[0]%2 == 0){
            i = 0;
        }
    }

    return e;
}

I believe this code is right but I am getting 0's for all numbers in the Array the Array is { 5, 15, 24, 35, 2, 7, 8} 我相信这段代码是正确的,但是我得到的所有数字都为0,数组为{5,15,24,35,2,7,8}

I believe your code isn't correct. 我认为您的代码不正确。
First of all, it is quite surprising you don't get an infinite loop. 首先,令人惊讶的是您没有遇到无限循环。 It is not done to mess with the loop-variable in a for-loop. 不会在for循环中弄乱循环变量。 If you would want to do that, use a while-loop. 如果您想这样做,请使用while循环。
Second point is that your if-statement contains e, which is up to that point not initialised, and thus only contains variables = 0. 第二点是您的if语句包含e,直到该点尚未初始化,因此仅包含变量= 0。
Third point: you always check for the same value e[0], so you only check the first value of array e in every iteration 第三点:您始终检查相同的值e [0],因此您每次迭代时仅检查数组e的第一个值

I hope this helps you enough to correct the code by yourself now... (otherwise see the answer from beresfordt) 希望这对您有所帮助,现在您可以自己更正代码...(否则请参阅beresfordt的答案)

There's several problems; 有几个问题。

  • e[] is not having any values populated in it, it is just being initialised with the length of a e []中没有填充任何值,只是使用a的长度进行初始化
  • you are setting i to equal zero in your if statement, you probably mean to set e[i] = 0 您在if语句中将i设置为零,则可能意味着将e [i]设置为0
  • you are only comparing e[0] %2 == 0, you probably mean to compare e[i] % 2 ==0 您只比较e [0]%2 == 0,您可能是想比较e [i]%2 == 0

putting it all together the for loop you intended to write was probably: 将所有内容组合在一起,打算编写的for循环可能是:

int e[] = a.clone();

for (int i = 0; i < a.length; i++){
    if( e[i]%2 == 0){
        e[i] = 0;
    }
} 

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

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