gpt4 book ai didi

java - Java 中的阶乘类

转载 作者:行者123 更新时间:2023-12-01 23:12:20 25 4
gpt4 key购买 nike

嗨,我目前正在做一项类(class)作业。所以我就完成了这段代码。但是,当 x number is < 0 时,如何阻止它返回数字? ?

public class Factorial {

public Factorial() {
System.out.print(new C1().computeFac(10));
}

/** First addicional class **/
private class C1 {

/** Fields **/
private int a,result = 1;

/** Method **/
public int computeFac(int input) {

if (input < 0) {
System.out.print(new C2().printError(0));
} else {

for ( a = 1 ; a <= input ; a++ )

result = result*a;
return (result);
}
return (result);
}
}

/** Second Addicional class **/
private class C2 {

/** Fields **/
String errosArray[] = {"Negative numbers are not aceptable! \nPlease try again!\n"};

public String printError(int a) {
return errosArray[a];
}

}

/** Main Method **/
public static void main(String [ ] args) {
Factorial factorial = new Factorial();
}

}

最佳答案

正常的方法是在此时抛出异常。所以你的代码看起来像:

        public int computeFac(int input) {
if (input < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
for ( a = 1 ; a <= input ; a++ ) {
result = result*a;
}
return result;
}

另外,请注意,对于循环和条件语句,始终使用大括号是个好主意,即使它们只有一行。

关于java - Java 中的阶乘类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com