I am trying to write a program that will take an integer and add up each of the number’s digits, count the number of digits in the number, and then average these two numbers.
I must use a while
loop and %
to access each of the individual digits. Use /
to reduce the number so that you can average all of the digits.
234 has a digit average of 3.0,
10000 has a digit average of 0.2,
111 has a digit average of 1.0
Here is my code:
import static java.lang.System.*;
public class DigitMath
{
private static int countDigits( int number )
{
int count = 0;
while( number > 0 )
{
count++;
number = number / 10;
}
return count;
}
private static int sumDigits( int number )
{
double total = 0;
while( number > 0 )
{
total = total + number % 10;
number = number / 10;
}
return number;
}
public static double averageDigits( int number )
{
if( number > 0 )
return sumDigits( number ) / countDigits( number );
return 0;
}
}
// other code
import static java.lang.System.*;
public class Lab09e
{
public static void main( String args[] )
{
out.println(DigitMath.averageDigits(234));
}
}