2015-10-20 155 views
-1

我用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(); 
    } 

} 
+0

請明確規定([編輯]您的文章)你的代碼是應該做的,什麼結果你期待,你會得到什麼,而不是。 –

+0

ProTip:不要多次初始化您的掃描器,也不要重寫傳入的值(您接受一個int [] x',然後立即用'x = new int [100]'來覆蓋)並且每個循環不要多次調用'in.nextInt()'。 – dcsohl

+0

不僅如此,而且試圖養成正確命名變量的習慣。很難知道像'x'和'n'這樣的變量會發生什麼。任何人都可以編寫代碼,但不是每個人都可以編寫別人可以閱讀的代碼。 –

回答

0

檢查這些循環:

這基本上把所有的整數x中。

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

這只是循環,直到它沒有它。

while(in.hasNextInt()); 

這意味着,if塊甚至不在循環中。然而,第一while循環後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++; 
    } 
相關問題