Home > Software design >  Amstrong number return in blank result (java)
Amstrong number return in blank result (java)

Time:10-07

public class Amstrong {

    public static void main(String[] args) {

        for (int i = 100; i < 1000; i  ) {

            String a = String.valueOf(i);

            int b = a.charAt(0);

            int c = a.charAt(1);

            int d = a.charAt(2);
            int e = b * b * b   c * c * c   d * d * d;

            if (e == i) {

                System.out.println(i);

            }

        }

    }

}

//Help me out please, no error occurred but the result returned in the blank

CodePudding user response:

You are not converting the characters to digits correctly.

One of the possible ways to fix it:

    int b = a.charAt(0)-'0';

    int c = a.charAt(1)-'0';

    int d = a.charAt(2)-'0';

Another way:

    int b = Character.digit (a.charAt(0),10);

    int c = Character.digit (a.charAt(1),10);

    int d = Character.digit (a.charAt(2),10);

Either way will give your the output:

153
370
371
407

CodePudding user response:

Another way you can do it is:

import java.util.*;
public class ArmstrongNumber3
{
     public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number");


        int n = sc.nextInt();

        int b = n;
        int sum = 0;
        int d = 0;
        while (n != 0) {
            d = n % 10;
            sum  = (d * d * d);
            n = n / 10;

        }
        if (sum == b) {
            System.out.println("Armstrong");

        } else
        {
            System.out.println("Not Armstrong");
        }









    }
}
  •  Tags:  
  • java
  • Related