Java Program to Check Armstrong Number

Java Program to Check Armstrong Number

Java Program to Check Armstrong Number

// Java program to check whether number is 
// armstrong or not

import java.util.*;

class DigitsOpr {
  private int num;

  //function to get value of num
  public void getNum(int x) {
    num = x;
  } //End of getNum()

  //function to check armstrong
  public boolean isArmstrong() {
    int n, sum, d;

    n = num; //keep value of num safe
    sum = 0;
    while (n > 0) {
      d = n % 10;
      sum += (d * d * d);
      n /= 10;
    }

    if (sum == num) return true;
    else return false;
  }
}

public class armstrong {
  public static void main(String[] s) {
    DigitsOpr dig = new DigitsOpr();
    int n;

    Scanner sc = new Scanner(System.in);

    //read number
    System.out.print("Enter a positive integer number: ");
    n = sc.nextInt();

    dig.getNum(n);
    if (dig.isArmstrong()) {
      System.out.println(n + " is an Armstrong number.");
    } else {
      System.out.println(n + " is not an Armstrong number.");
    }
  }
}
RUN 1:
Enter a positive integer number: 153
153 is an Armstrong number.

RUN 2:
Enter a positive integer number: 407
407 is an Armstrong number.

RUN 3:
Enter a positive integer number: 417
417 is not an Armstrong number.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment