我正在尝试解决这个问题:
a)用以下标头编写一个方法,该标头采用整数n和返回n的值! (发音为n阶乘),计算如下:
public static int factorial(int n)
注意,0! = 1和n! = n *(n-1)*(n-2)* ..... * 1。示例:factorial(4)将返回24,即= 4 * 3 * 2 * 1。
b)用以下标头编写一个方法,该标头采用整数x并且如果x是一个强数,则返回true。否则,它返回false。
public static boolean isStrongNumber(int x)
请注意,isStrongNumber
方法应调用阶乘方法来计算x中的每个数字。
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x){
int temp = x;
int z;
int q = 0;
int sum =0;
while(temp>0){
x=x%10;
z=factorial(x);
q+=z;
if (q==temp){
System.out.print(q+" ");
return true;
}
}
}
这是我的答案,但是每次尝试运行它时都会出错。
这无法编译,因为它在while循环之外缺少return语句。事实上,即使x <= 0对于exmaple,您也无法确保进入循环。您应该在方法末尾的循环外添加return false。另外,如果您遇到错误并在StackOverflow上写了一个问题,请复制错误消息,这将非常有帮助。
您未在isStrongNumber
方法的末尾返回布尔值
public static int factorial(int n) {
int f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int reminder = 0;
while (x > 0) {
reminder += factorial(x % 10);
if (reminder == temp) {
System.out.print(reminder + " ");
return true;
}
x /= 10;
}
return false;
}