在JAVA中怎么计算偶数积,如何计算Java中的多位数字中的奇数,偶数和零数?

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)

or

Input: 2034

Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)

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);

}

}

Sorry, the code formatted weirdly in the textbox.

解决方案

value = value % 10;

Probably the end-all-be-all of your problems.

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.

I suggest something more like this:

while (value > 0) {

if ((value%10)==0) {

zeroCount++;

}

else if (value%2==0) { //As per comment below...

evenCount++;

}

else {

oddCount++;

}

value /= 10;

}

Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值