为什么以下代码返回错误的答案?

时间:2018-06-12 18:04:00

标签: java

我在这里比较 ArmstrongNo & out 都具有相同的值( 371 ),但是打印错误的声明。

public class ArmstrongNumber {

static int ArmstrongNo = 371;
static int sum = 0;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ArmstrongNumber am = new ArmstrongNumber();
    int out = am.Armstrong();
    System.out.println(out);
    if (ArmstrongNo == out)
        System.out.println("It is an Armstrong number");
    else
        System.out.println("Not an Armstrong number");

}

public int Armstrong() {

    int length = String.valueOf(ArmstrongNo).length();// To find the length of integer
    for (int x = 0; x < length; x++) {
        int i = ArmstrongNo % 10;
        int cube = i * i * i;
        sum += cube;

        ArmstrongNo = ArmstrongNo / 10;
    }
    return sum;
 }

}

输出:

371

不是阿姆斯特朗号

2 个答案:

答案 0 :(得分:4)

您正在覆盖ArmstrongNo ArmstrongNo = ArmstrongNo / 10;

总和则为371但ArmstrongNo为0

修改

这会修复您的代码(至少在功能上)

public int Armstrong() {
        int ArmstrongNoCopy = ArmstrongNo;
        int length = String.valueOf(ArmstrongNoCopy)
                .length();// To find the length of integer
        for (int x = 0; x < length; x++) {
            int i = ArmstrongNoCopy % 10;
            int cube = i * i * i;
            sum += cube;

            ArmstrongNoCopy = ArmstrongNoCopy / 10;
        }
        return sum;
    }

答案 1 :(得分:0)

您的方法public int Armstrong()修改了静态变量ArmstrongNo。为避免这种情况,请将此静态变量声明为final并将局部变量添加到方法public int Armstrong()

final static int ArmstrongNo = 371;

public int Armstrong() {

    int ArmstrongNo = ArmstrongNumber.ArmstrongNo;
    //...
}