簡體   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