while (condition) { ... } keeps running as long as the condition is true; use it when the number of rounds is not known in advance. Something in the body must move toward the condition becoming false, or the loop never ends; the lesson runner stops runaway code after a while and tells you.
n / 10 chops the last digit off a whole number and n % 10 reads it, which is how a loop walks through digits. do { ... } while (condition); is the variant that always runs the body at least once.
The library project checks member card numbers with a simple checksum: the digits of a valid card add up to a multiple of ten. This lesson adds the class Checksum that does the adding.
int n = 1, steps = 0;
while (n < 100) {
n *= 2;
steps++;
}
System.out.println(n + " " + steps); // 128 7Your task
In Main, write static int digits(long n) returning how many digits a non-negative whole number has, by repeatedly dividing by 10 (digits(0) is 1).
In the class Checksum, write static int digitSum(long n) returning the sum of the digits of a non-negative number, so digitSum(1234) is 10.
Part of the final project. Checksum adds up the digits of a card number; a valid card sums to a multiple of ten. It is saved in this browser and loaded into Project: the library when you get there.
Hint 1
digits: handle 0 first, then int count = 0; while (n > 0) { n /= 10; count++; }
Hint 2
digitSum: while (n > 0) { sum += n % 10; n /= 10; } and n % 10 is a long, so cast it: sum += (int) (n % 10);
Show the solution
public class Main {
static int digits(long n) {
if (n == 0) {
return 1;
}
int count = 0;
while (n > 0) {
n /= 10;
count++;
}
return count;
}
public static void main(String[] args) {
System.out.println(digits(12345) + " " + Checksum.digitSum(12345));
}
}
class Checksum {
static int digitSum(long n) {
int sum = 0;
while (n > 0) {
sum += (int) (n % 10);
n /= 10;
}
return sum;
}
}