gpt4 book ai didi

java - 条件和循环练习

转载 作者:行者123 更新时间:2023-11-30 03:01:35 25 4
gpt4 key购买 nike

我坚持做一个练习,它说“编写一个程序,确定并打印从键盘读取的整数值中的奇数、偶数和零位数。我做错了什么以及如何纠正我的错误?”错误?

import java.util.Scanner;

public class OddEven {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);

int odd=0;
int even=0;
int zero=0;
int num=0;
int value;

System.out.println("Enter a value: ");
value=scan.nextInt();
if (value%2==0)
even=even+1;
else
odd=odd+1;
System.out.println("even = "+ even);
System.out.println("odd = "+odd);
System.out.println("zero = "+zero);
}
}

最佳答案

您必须一次检查每个数字:

int odd, even, zero, value;
value = scan.nextInt();

while(value > 0) {
int digit = value%10; //isolates only the last digit
if(digit==0)zero++;
else if(digit%2==0)even++;
else odd++;
value /= 10; //removes the last digit
}

关于java - 条件和循环练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35811712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com