2014-10-11 95 views
-2

好了,所以我的目標是要完成以下任務:比較數組元素爲零?

「設計和實現一個從鍵盤讀取一個整數值,確定並打印的奇數,偶數和零個的位數的應用

提示,標籤和輸出的規範:你的代碼根本沒有任何提示,這個程序的輸入是一個整數,在整數被讀取後,輸出由三行組成,第一行由第二行由整數中的偶數位數和後跟標號「偶數位」組成,第三行由整數中的零位數組成由標籤「零位」。例如,如果173048被讀取,輸出將是: 3奇數字 3連位 1零位 規格的名字:您的應用程序類應該叫DigitAnalyst」

而且我已經生成的代碼是:

import java.util.Scanner; 
public class DigitAnalyst{ 
public static void main(String[] args){ 
    Scanner scan = new Scanner(System.in); 
    String num = scan.next(); 
    int odd_count = 0; 
    int even_count = 0; 
    int zero_count = 0; 
    //input an int as a string, and set counter variables 

    int[] num_array = new int[num.length()]; 
    //ready a array so we can so we can parse it sanely 
    for (int i =0; i < num.length(); i++) 
    { 
     num_array[i] = num.charAt(i); 
    }//fill the array with the values in the initial number using a loop 

    for (int i=0;i< num_array.length; i++) 
    { 
     if (num_array[i] % 2 ==0) 
     { 
      if (num_array[i] ==0)//the hell is going on here? 
      { 
       zero_count++; 
      } 
      else if (num_array[i] != 0) 
      { 
       even_count++; 
      } 
     } 
     else if (num_array[i] % 2 != 0) 
     { 
      odd_count++; 
     } 
    }//use this loop to check each part of the array 

    System.out.println(odd_count+ " odd digits"); 
    System.out.println(even_count+" even digits"); 
    System.out.println(zero_count+" zero digits"); 

} 

}

然而,我不斷收到錯誤的輸出更具體地說,它返回奇數正確的金額,但它使計數0作爲甚至不作爲零

我知道問題出在哪裏,但我不知道什麼是錯的,我已經花了幾個小時。 如果有人能指出我在正確的方向,我會是ectstatic。

+1

你可能想看看'charAt()'實際返回什麼,你沒有比較你的想法。 – 2014-10-11 21:38:52

回答

1

當你遇到涉及的在整數位的操作有問題,標準的方法是使用一個實際的整數,運營商%,而不是字符串。取而代之的scan.next()使用

int num = scan.nextInt(); 

然後你可以這樣做:

do { 
    int digit = num % 10; 

    if (digit == 0) { 
     zero_count ++; 
    } else if (digit % 2 == 0) { 
     even_count ++; 
    } else { 
     odd_count ++; 
    } 

    num /= 10; 

} while (num > 0); 

的想法是,當你除以10多家,其餘的也正是最右邊的數字,以及商將有所有其他數字。這就是十進制系統的工作原理。

在這種方法中,你直接得到數字而不用調用任何方法,並且你不需要任何數組。

1

如果將整數元素分配給num.charAt(i),則會分配該字符的ASCII值,並且會得到錯誤的結果。爲了解決這個問題,改變

num_array[i] = num.charAt(i);

num_array[i] = Integer.parseInt(String.valueOf(num.charAt(i))); 或相似。

0

我會在這裏給你一些幫助。首先,charAt()返回字符串索引處的字符,作爲char數據類型。您正在以ints的數組進行存儲,該數組假定組中字符的數值,而不是實際值。

試試這個...

變化:

int[] num_array = new int[num.length()]; 

到:

char[] num_array = new char[num.length()]; 

,敷在你的條件語句與您的所有num_array[i]引用:

Character.getNumericValue(num_array[i]) 

你應該得到你的預期結果。

Input = 12340 
Output = 
2 odd digits 
2 even digits 
1 zero digits