好了,所以我的目標是要完成以下任務:比較數組元素爲零?
「設計和實現一個從鍵盤讀取一個整數值,確定並打印的奇數,偶數和零個的位數的應用
提示,標籤和輸出的規範:你的代碼根本沒有任何提示,這個程序的輸入是一個整數,在整數被讀取後,輸出由三行組成,第一行由第二行由整數中的偶數位數和後跟標號「偶數位」組成,第三行由整數中的零位數組成由標籤「零位」。例如,如果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。
你可能想看看'charAt()'實際返回什麼,你沒有比較你的想法。 – 2014-10-11 21:38:52