如何计算Java中的多位数字中的奇数,偶数和零数? [英] How can I count the number of odd, evens, and zeros in a multiple digit number in Java?
问题描述
基本上,我需要编写一个程序,它以整数形式接受用户输入并包括 2 ^ 31 -1
,并返回奇数,偶数,和int中的零数。例如,
Basically I need to write a program that takes user input up to and including 2^31 -1
in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
或
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
我确定我在想,但我不能放慢我的大脑。任何人可以帮助?
这是代码的第三次迭代,前两个是尝试使用for循环。
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help? This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
对不起,代码格式在文本框中奇怪。 / p>
Sorry, the code formatted weirdly in the textbox.
推荐答案
value = value % 10;
可能是所有的问题。
如果 value
是 2034
,则 value%10
返回
block,then do 4
...然后将该值赋给 value
c $ c> if else 4/10
get 0
退出 while循环
,而不寻址其他3位数。
If value
is 2034
, then value % 10
returns 4
... and then assigns that value to value
, you go through your if else
block, then do 4/10
get 0
, and exit the while loop
without addressing the other 3 digits.
我建议更像这样:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
或 int thisDigit = value%10
,然后在
中替换
value 如果
thisDigit
。
这篇关于如何计算Java中的多位数字中的奇数,偶数和零数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!