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();
}
}
}
factis not reset between loops. Keep in mind that fact has to be declared in the calculator methodlong fact=1;as well as inmain().staticmethod can invoke only another static methods from the same class. Yourmainmethod is static, so if you want to callcalculatorit must be static too. You can refer to the static keyword here or to this post.java static keywordand there will be tons of info for you. Maybe you want to learn more of Java keywords and their use :D.