[英]Why isn't this if statement returning the boolean value?
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.
如果因子的总和等于输入的数字,我想返回true但是它不会这样做。
I have tried moving the if statement all over the code and it doesn't work anywhere. 我试过在代码中移动if语句,它在任何地方都不起作用。
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. 我希望当代码看到sumOfFactors将sum =输入的数字,并且当我得到true语句时,当发生这种情况时,它不会返回true。 In fact, it doesn't return anything and states that the method returns were not used.
实际上,它不会返回任何内容并声明方法返回的内容未被使用。
It "isn't working" because you aren't printing the result. 它“无效”,因为您没有打印结果。
public static void main(String[] args) {
isPerfectNumber(28);
}
should be 应该
public static void main(String[] args) {
System.out.println(isPerfectNumber(28));
}
which is "true". 这是“真实的”。 Also,
也,
if (sumOfFactors == number) {
return true;
} else {
return false;
}
is a long way to write 写作还有很长的路要走
return sumOfFactors == number;
And, if you're using Java 8+, your isPerfectNumber
method can be written as a one-liner with an IntStream
and a lambda filter like 而且,如果你使用的是Java 8+,你的
isPerfectNumber
方法可以写成一个带有IntStream
和lambda过滤器的IntStream
public static boolean isPerfectNumber(int number) {
return number >= 1 && IntStream //
.range(1, number) //
.filter(i -> number % i == 0) //
.sum() == number;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.