-3

Here I'm comparing ArmstrongNo & out were both have same values(371), but is printing the wrong statement.

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;
 }

}

OUTPUT:

371

Not an Armstrong number

suze
  • 3
  • 6

2 Answers2

4

you are overwriting your ArmstrongNo here ArmstrongNo = ArmstrongNo / 10;

sum is then 371 but ArmstrongNo is 0

EDIT

this fixes your code (at least functionally)

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;
    }
NiVeR
  • 9,644
  • 4
  • 30
  • 35
Michal
  • 970
  • 7
  • 11
0

Your method public int Armstrong() modifies static variable ArmstrongNo. To avoid this, do declare this static variable as final and add local variable to the method public int Armstrong():

final static int ArmstrongNo = 371;

public int Armstrong() {

    int ArmstrongNo = ArmstrongNumber.ArmstrongNo;
    //...
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35