java - Java中的DigitSum方法

标签 java debugging variables methods parameters

为了遵循“Java 的艺术与科学”这本书,我正在做一些练习程序。该程序旨在读取整数n并返回位数

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;

}

关于java - Java中的DigitSum方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476682/

相关文章:

java - 在运行时更新默认值并在 android studio 中使用新值进行计算

java - 调试递归方法来查找单词是否存在于滑板中

debugging - mac osx 数据库访问/崩溃

bash - 如果循环将输出发送到管道,则重置全局变量

javascript - 第一类使用的这两个函数有什么区别? (javascript)

php - load local infile 中 @var 的上下文是什么

java - Maven 存储库中 4.1.1 中的 spring-security-web 在哪里?

java - Android sqlite - "No such table"而表存在

java - 即使在调用cancel之后,倒数计时器的onTick方法仍然被调用

python - 调试Python代码的方法?