To Find out whether a number is Armstrong number
Armstrong number is a
number that is the sum of its own digits each raised to the power of the number
of digits.
Let us Look at how to find out whether the number is
Armstrong using java.
Note: The input is saved in Text file.
Input:
7
181
153
Output:
True
False
True
import java.io.BufferedReader;
import
java.io.FileNotFoundException;
import
java.io.FileReader;
import
java.io.IOException;
import
java.io.File;
public
class Armstrong {
public static void main (String[] args) throws
FileNotFoundException,NumberFormatException{
File file = new File(args[0]);
BufferedReader in = new BufferedReader(new FileReader(file));
int len;
String currentline;
double num;
int y;
int sum = 0;
char z;
try
{
while ((currentline = in.readLine()) != null)
{
len=currentline.length();
if(len>1)
{
for(int i=0;i<currentline.length();i++)
{
z=currentline.charAt(i);
y=Character.getNumericValue(z);
num=Math.pow(y,
len);
sum+=num;
}
}
else
{
sum=Integer.parseInt(currentline);
}
if(sum==Integer.parseInt(currentline))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
sum=0;
}
}catch (IOException e) {
e.printStackTrace();
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}
Comments
Post a Comment