Monday, February 21, 2011

Armstrong Number Java Program

An Armstrong Number is one in which the sum of the individual numbers raised to the power of the number of words in that number is equal to that particular number itself. For example 1 raised to the power 1 is equal to 1, so it is an Armstrong Number. Again 153, implies 1 raised to the power 3, 5 raised to the power 3, and then 3 raised to the power 3 are added, then it gives 153 again, so it is also an Armstrong Number.
The Java Code is given below:-
////////////////////////////////////
package developer;
import java.util.Scanner;
public class ArmstrongNumber {
static double finalValue = 0;
public static void main(String[] args) {
int valueTaker = 0;
System.out.println("Enter a number to be checked for Armstrong Number: ");
Scanner armstScan = new Scanner(System.in);
if(armstScan.hasNextInt())
{
valueTaker = armstScan.nextInt();
}
StringBuffer sb = new StringBuffer().append(valueTaker);
double lengthSBKeeper = sb.length();
for(int lengthKeeper = 0; lengthKeeper < sb.length(); lengthKeeper++)
{
double zxc = Integer.parseInt(sb.substring(lengthKeeper, lengthKeeper+1));
finalValue = Math.pow(zxc, lengthSBKeeper) + finalValue;
}
if(finalValue == valueTaker)
{
System.out.println("The entered number "+valueTaker+" is an Armstrong Number");
}
else
{
System.out.println("The entered number is not an Armstrong Number");
}
}
}
///////////////////////////////////////

No comments:

Post a Comment

Chitika