我对while循环感到困惑吗?您能否说出while循环内的条件是什么?即()? [关闭]

问题描述 投票:-5回答:1
//Find the number of odd, evens, and zeros digits from integers value given from keyboard

import java.util.Scanner;

public static void main(String[] args) 

    int number, countOdds = 0, countEvens = 0, countZeros = 0;
    Scanner input = new Scanner(System.in);

    //Take input from users
    System.out.print("Enter a number from 0 to 100 : ");
    number = input.nextInt();

    //Conditions 

    do {
        int checkNum = num % 10;
        if(checkNum % 2 == 0) {
            countEvens++;
        }
        else if(checkNum == 0) {
            countZeros++;
        }
        else {
            countOdds++;
        }

        num /= 10;

    }while(num >= 0);

    System.out.print("Evens are : " + countEvens);
    System.out.print("Odds are : " + countOdds);
    System.out.print("Zeros are : " + countZeros);
java while-loop do-while
1个回答
0
投票

由于零是偶数,所以您的解决方案会将所有零算作偶数,并且countZeros变量将永远不会递增。

您需要切换条件的顺序:

do {
    int checkNum = num % 10;
    if(checkNum == 0) {
        countZeros++;
    }
    else if(checkNum % 2 == 0) {
        countEvens++;
    }
    else {
        countOdds++;
    }

    num /= 10;
} while(num >= 0);
© www.soinside.com 2019 - 2024. All rights reserved.