codingisntmyfavorite codingisntmyfavorite - 1 month ago 5
Java Question

Need assistance with a while loop to make the print statement work

Design and implement an application that determines and prints
the number of even, odd, and zero digits in an int value read from the keyboard.

Example:

Enter a number: 100504575
The number: 100504575 has 3 zeros, 1 evens, and 5 odds.


so the code is saying to enter a number, then it'll count how many evens odds and zeros, then it will print that number again and say how many evens odds and zeros there are. the counting part works i just can't get the num part to work in this print statement. if i entered the number 1384932 it should print back out: The number: 1384932 has 0 zeros, 3 evens, and 4 odds. currently it prints out: The number: 0 has 0 zeros, 3 evens, and 4 odds.

System.out.print("The number: " + num + " has " + zero + " zeros, "
+ even + " evens, " + "and " + odd + " odds.");

import java.util.Scanner;

public class CountDigits {

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

Scanner Scan = new Scanner(System.in);
int even =0, odd = 0, zero = 0;
System.out.print ("Enter a number: ");
int num = Scan.nextInt();
while(num > 0) {
int digit = num % 10;
num /= 10;
if(digit == 0) {
zero++;
} else if(digit % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.print("The number: " + num + " has " + zero + " zeros, "
+ even + " evens, " + "and " + odd + " odds.");
Scan.close();
}
}

Answer

num will be 0 since that's your sentinel value to stop the loop. No problem, just copy the input into another variable that will be used in the while loop.

int num = Scan.nextInt();
int looper = num;
while (looper > 0) { ... }

This way num retains the value taken with the Scanner and the other is the one altered during the loop. Of course, you'll need to refactor all instances of num to be looper inside the while loop as well. You can do that with a Replace All very easily.