I’m unsure how to use the static method in this program. I am coding a program that will calculate a factorial of a number between 0 and 10. The user can enter the number and the program should calculate the factorial.
I had originally written a functional program with all of the code coming from the main and then when I double checked the assignment rubric I noticed I was supposed to place the calculation for getting the factorial in a static method. I believe my issue is towards the bottom where I’m asking the user to enter the number I don’t send it to the calculator. I guess I’m unclear on how that is done. I’m new so I apologize for my poor coding and I appreciate any help.
Here is my code:
import java.util.Scanner; //import scanner class
public class FactorialCalculator {
public static long calculator(long fact, int num) {
for(int i = 1; i<=num; i++) {
fact *= i;
}
return fact;
}
public static void main(String[] args) {
Scanner calc = new Scanner(System.in); //create new scanner calc
int num = 0;
long fact = 1;
//welcome user to the Factorial Calculator
System.out.println("Welcome to the Factorial Calculator.");
System.out.println();
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
System.out.println("Please enter an integer that's greater than 0 and less than 10: ");
num = calc.nextInt();
System.out.println("The Factorial for " + num + " is " + fact +".");
System.out.println();
System.out.println("Would you like to continue? y/n");
choice = calc.next();
System.out.println();
}
}
}
You’re never calling
calculator(long fact, int num);just call it with
right after:
EDIT:
I would recommend you also remove the
long factas an argument tocalculator()and add it into the method body ofcalculator()Ex: