I am trying to make a program that will show if an input is a perfect number meaning the factors (not including the number) add up to be the same as that number. I got it working other than the return value. I want to return true if the sum of the factors is equal to the number entered however it just won't do it.
I have tried moving the if statement all over the code and it doesn't work anywhere.
public class Main {
public static void main(String[] args) {
isPerfectNumber(28);
}
public static boolean isPerfectNumber(int number) {
if (number < 1) {
return false;
}
int numberToTest = 1;
int sumOfFactors = 0;
while (numberToTest < number) {
if (number % numberToTest == 0) {
sumOfFactors += numberToTest;
}
numberToTest++;
}
if (sumOfFactors == number) {
return true;
}else{
return false;
}
}
}
I expect that when the code see that the sumOfFactors will have the sum = to the number entered and that's when I get the true statement however when that happens it doesn't return true. In fact, it doesn't return anything and states that the method returns were not used.
Aucun commentaire:
Enregistrer un commentaire