2014-10-11 133 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