Java 中的 DigitSum 方法

DigitSum method in Java

努力按照 "Art and science of Java" 的书做一些锻炼计划。该程序旨在读取整数 n 和 return 位数

import acm.program.*;

public class DigitSum extends ConsoleProgram {
    public void run() {
        println("This program tells you how many digits is in a number");
        int n = readInt("Enter the number which you want to check: ");
        int dSum =0;
        println("The number of digits is: "+myMethod(n,dSum));
    }
    private int myMethod (int n, int dSum) {
        while (n>0) {
            dSum += n%10;
            n /= 10;
        }
        return dSum;

    }

}

有人能告诉我为什么我的程序没有按预期运行吗?如果我 运行 它并将 n 设置为 555,它表示位数是 15,这显然是不正确的。

因为您要添加 5+5+5,即 15。

如果你想要位数那么你需要使用计数器。

private int myMethod (int n, int dSum) {
    int counter = 0;
    while (n>0) {
        dSum += n%10;
        n /= 10;
        counter++;
    }
    return counter;

}