case "ja":
System.out.println("Ievadiet vardu");
String x = input.next();
n = x.length();
{
long fact;
fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
sum += fact;
}
}
break;
case "ne":
Scanner in = new Scanner(System.in);
System.out.println("Ievadiet ciparu");
n = in.nextInt();
if ( n < 0 ){
System.out.println("Ciparam jabut pozitivam.");
}
{
long fact;
fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
sum += fact;
}
}
break;
我正在尝试创建一个可以计算阶乘总和的方法,这样我就可以缩短这个代码但是我只做了简单的方法而且没有想法如何让方法输出sum
和如何正确地呼吁它。
答案 0 :(得分:1)
您可以像这样添加getFactorialSum
方法
// private means only this class can call the method.
private static long getFactorialSum(int n) {
long fact = 1;
long sum = 0;
for (int i = 1; i <= n; i++) {
fact *= i;
sum += fact;
}
return sum;
}
然后你就可以这样称呼它
String x = input.next();
n = x.length();
long factorialSum = getFactorialSum(n);