繁体   English   中英

数组中的数字如何计数为奇数或偶数?

[英]How can the numbers in array count to odd or even number?

我用java编写了代码,但它不算是奇数或偶数。 它只计算偶数。 如果我错过了什么?

import java.util.Scanner;

public class OddEven {
    //create the check() method here
    static void check(int[] x, int n) {
        x = new int[100];
        Scanner in = new Scanner(System.in);

        while (in.hasNextInt()) {
            x[n++] = in.nextInt();
        }

        if (x[n] % 2 == 0) {
            System.out.println("You input " + n + " Even value");
        } else if (x[n] % 2 == 1) {
            System.out.println("You input " + n + " Odd value");
        }
        while (in.hasNextInt()) ;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        //read the data here
        System.out.print("Input a list of Integer number : ");

        int[] x = new int[100];
        int n = 0;
        check(x, n);

        in.close();
    }

}

检查这些循环:

这基本上将所有整数放入 x 中。

 while(in.hasNextInt()) {
        x[n++] = in.nextInt();  
    }

这只是循环,直到它没有它。

while(in.hasNextInt());

这意味着, if 块甚至不在循环中。 但是,第一个 while 循环 post 递增 n,这意味着即使您有一个数字,它也会分配:

x[0] = 123;

但是然后n = 1。 这意味着, if 块将检查下一个字段。 但默认情况下它是 0,这将显示它是偶数。

这会更有意义:

x= new int[100];
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
        x[n] = in.nextInt();  

         if(x[n]%2==0){

             System.out.println("You input "+n+" Even value");

         }else if(x[n]%2==1){

             System.out.println("You input "+n+" Odd value");

         }
         n++;
   }

暂无
暂无

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

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