猿问

如何检查所有其他元素是否偶数

我的代码仅适用于第一个索引,它只返回8 true.


nums[0]例如,如果我将第一个索引 ( )更改为 9,它会跳过3并打印4 true.


我如何制作以便它检查其余的元素(每个其他元素),以便它适用于每个其他索引?


public static boolean solution(int[] nums) {

    for(int i = 0; i < nums.length; i++) {

        if(i % 2 == 0 && nums[i] % 2 == 0) {

            System.out.print(nums[i] + " ");

            return true;

        }

    }

    return false;

}


public static void main(String args[]) {

    int[] nums = {8,3,4,1,6,5,12,1};

    System.out.println(solution(nums));

}


米琪卡哇伊
浏览 229回答 3
3回答

慕前端3368111

我认为你想要做的是检查所有偶数索引,看看是否有你可以这样做:public static boolean solution(int[] nums) {   for(int i = 0; i < nums.length; i++) {     if(i % 2 == 0 && nums[i] % 2 != 0) {         System.out.print(nums[i] + " ");         return false;     }   }   return true;}

拉风的咖菲猫

您的代码中有一个(逻辑)错误,还有一个可以改进的部分:public static boolean solution(int[] nums) {&nbsp; &nbsp; for(int i = 0; i < nums.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(i % 2 == 0 && nums[i] % 2 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(nums[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false;}在您当前的代码中,在第一个有效测试时返回 true,这意味着您不测试以下情况。更改您的代码,以便您对它们进行全部测试,并且仅在遇到无效值时才在流程中返回。public static boolean solution(int[] nums) {&nbsp; &nbsp; for(int i = 0; i < nums.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(i % 2 == 0 && nums[i] % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(nums[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true;}您可以改进的第二件事是不检查每次迭代的偶数索引。只需将您的 i 值增加两个而不是一个:public static boolean solution(int[] nums) {&nbsp; &nbsp; for(int i = 0; i < nums.length; i+=2) {&nbsp; &nbsp; &nbsp; &nbsp; if( nums[i] % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(nums[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true;}

LEATH

我认为你想要做的是检查所有偶数索引,看看是否有你可以这样做:public static boolean solution(int[] nums) {&nbsp; &nbsp;for(int i = 0; i < nums.length; i++) {&nbsp; &nbsp; &nbsp;if(i % 2 == 0 && nums[i] % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print(nums[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp; &nbsp;return true;}
随时随地看视频慕课网APP

相关分类

Python
我要回答