Reputation: 27
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;
I'm trying to create a method that could calculate the sum of factorials so I can make this code shorter but I've made only simple methods and have no Idea how to get the method to output sum
and how to properly call for it.
Upvotes: 0
Views: 116
Reputation: 201447
You could add a getFactorialSum
method like this
// 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;
}
And then you could call it like this
String x = input.next();
n = x.length();
long factorialSum = getFactorialSum(n);
Upvotes: 1