I'll concentrate mainly on shortening lines and removing unnecessary code lines as it heavily increases the readability of the source code.
#main(String[] args)
The first thing I noticed is that you call the method #armstrong(int number)
two times when you only need to call it one time. This is important because it affects your performance as Java will have to process the method but you don't do anything with the result.
System.out.println(armstrong(number));
Instead of:
armstrong(number);
System.out.println(armstrong(number));
You don't even have to save the number to a variable but you can do that for the extra bit of readability. I would simply directly call Scanner#nextInt()
as it shortens the main method.
System.out.println(armstrong(in.nextInt()));
Closing the Scanner
You should also close the Scanner
after you used it for the last time for several reasons:
- Garbage collection can only manage memory, not other system resources. If your Java program has plenty of free memory, garbage collection will not be triggered automatically and your
Scanner
will still remain open.
- A stream, which a
Scanner
uses, kept open, can sometimes stay open until the kernel decides to close it.
in.close();
#armstrong(int number)
In the while loop you can shorten some mathematical operations by using /=
and +=
. This adds a bit more readability to the program as it shortens those lines.
number /= 10;
sum += Math.pow(temp, 3);
Data types
You can change the data type of the variable sum to an int
as you don't make anything with the variable that would require numbers that are not natural numbers:
int sum = 0;
Return statements
Here, you have two possibilities of shortening this, one is using inline checks and the otherone is a rather standard method of avoiding else
blocks.
if (sum == oldNumber) {
return "armstrong number";
}
return "not armstrong number";
This is basically the same but you don't need to include an else
-statement as everything that applies to the if
-check is already returned and the rest is automatically the else
case. The other method is the following:
return (sum != oldNumber ? "not " : "") + "armstrong number";
Personally, I prefer the second method because I got used to using these inline-checks.
Putting it all together
import java.util.Scanner;
public class ArmstrongCheck {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if (!in.hasNextInt()) {
System.out.println("error");
}
System.out.println(armstrong(in.nextInt()));
}
private static String armstrong(int number) {
int sum = 0, oldNumber = number;
while (number > 0) {
int temp = number % 10;
number /= 10;
sum += Math.pow(temp, 3);
}
return (sum != oldNumber ? "not " : "") + "armstrong number";
}
}