gpt4 book ai didi

java - 构造函数中的逻辑?

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:16 24 4
gpt4 key购买 nike

下面的代码工作正常,但我想知道对象创建时是否有任何问题。

import java.util.Scanner;

public class FactorialExample {
public FactorialExample(int n) {
int fact=1;
for(int i=1;i<=n;i++) {
fact=fact*i;
}
System.out.println("the factorial of a given number is::"+fact);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Integer Value:");
int value=sc.nextInt();
FactorialExample fe=new FactorialExample(value);

}
}

最佳答案

是的,您的假设是正确的 - 不要在构造函数中使用业务逻辑。

至多,初始化对象状态。

否则,异常处理、测试和模拟等事情会变得困难。

在您的代码中,您可以完全避免使用构造函数,事实上:

import java.util.Scanner;

public class FactorialExample {
int solve(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
return fact;
}

public static void main(String[] args) {
FactorialExample fe=new FactorialExample();
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Integer Value:");
int value=sc.nextInt();
int solution = fe.solve(value);
System.out.println("tha factorail of a given number is::"+solution);
}
}

关于java - 构造函数中的逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24038907/

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