Armstrong Number Java Program
Overview
In this post, we will discuss the Armstrong number java program. We will try to write the Java program that checks the number if its Armstrong number or not. First of all, an Armstrong number is an n-digit number that is equal to the sum of the nth powers of its individual digits.
Let n be the Armstrong number with x digits then the equation is:
F{ N,x } = n1x + n2x + n3x + nx-1x + nxx
Simple example is numbers are 0 , 1 , 2 , 3 , 4, 5 ,6 ,7 ,8, 9
Another example:
153 = 13 + 53 + 33
Sample code listing
Sample code to check a number is Armstrong number or not is below :
package com.testingdocs.javaautomation; import java.util.Scanner; public class ArmStrongNumber { private static Scanner scanner; public static void main(String args[]) { System.out.println("Please enter a number to check:"); try{ scanner = new Scanner(System.in); int inputNumber = scanner.nextInt() ; int n = inputNumber ; int power = numberofdigits(n); System.out.println("Checking Number ... : " + n); System.out.println("Number of Digits : " + power); int check=0,remainder; while(inputNumber > 0) { remainder = inputNumber % 10; check = check + (int)Math.pow(remainder,power); inputNumber = inputNumber / 10; } if(check == n) System.out.println(n + " is an Armstrong Number"); else System.out.println(n + " is not an Armstrong Number"); } catch(Exception e) { System.out.println("Error occurred. Computation Failed"); } finally { scanner.close(); } } private static int numberofdigits(int number) { int numdgits = 0; do { number = number / 10; numdgits++; } while (number > 0); return numdgits; } }
We will run the above code with sample test cases. For any program we write, we need to run against some test cases to check the working of the program.
Sample output for example number 153 as shown below:
Please enter a number to check:
153
Checking Number … : 153
Number of Digits : 3
153 is an Armstrong Number
Notes:
Scanner class reads the input from the standard input. The method numberofdigits() gets the number of digits of the input number. The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. In the finally block, we have closed the scanner to prevent resource leak.
Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :
https://www.oracle.com/in/java/