I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker. //An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.// If I understand this concept correctly, then my code should work fine but I really dont know where I made mistakes. I would appreciate if you correct my mistakes but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
if(result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used ‘153’ as an input. Thank you for your help!
>Solution :
There are a few mistakes here.
First, you aren’t raising each digit to the power of 3, but to the power of the length on the number (which actually is 3 in the specific case of 153, but is generally wrong).
More importantly, you aren’t summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', 3);
}
Having said that, it’s arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration:
int temp = input;
int result = 0;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, 3);
temp /= 10;
}