我不确定如何在此程序中使用静态方法。我正在编写一个程序,它将计算0到10之间的数字的阶乘。用户可以输入数字,程序应该计算阶乘。 我最初编写了一个函数程序,其中包含来自main的所有代码,然后当我仔细检查赋值量时,我注意到我应该放置计算以获取静态方法中的阶乘。我相信我的问题是在我要求用户输入我不将其发送到计算器的号码的底部。我想我不清楚这是怎么做的。我很新,所以我为我糟糕的编码道歉,我感谢任何帮助。
这是我的代码:
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();
}
}
}
答案 0 :(得分:1)
在打印结果之前放置它:
fact = FactorialCalculator.calculator(fact, num)
答案 1 :(得分:0)
由于您的calculator
方法是静态方法,因此您可以使用类名直接调用它。
num = calc.nextInt();
long result_factorial = FactorialCalculator.calcuator(fact,num)
你的方法应该是
public static long (int num)
{
long fact = 1;
for(int i = 1; i<=num; i++)
{
fact *= i;
}
return fact;
}
从主方法中删除fact
初始化。
答案 2 :(得分:0)
你永远不会打电话给calculator(long fact, int num);
只需用
调用它 fact = calculator(fact,num);
之后:
num = calc.nextInt();
修改强>
我建议你删除long fact
作为calculator()
的参数,并将其添加到calculator()
例如:
public static long calculator(int num){
long fact=1;
for(int i = 1; i<=num; i++){
fact *= i;
}
return fact;
}
答案 3 :(得分:0)
您可以将类的静态方法称为:
variableType variableName = ClassName.MethodName(parameters);
在您的情况下,您只需致电:
fact = FactorialCalculator.calculator(fact, num);
当您向用户询问输入数量时,以及在向用户打印事实编号之前,应将其插入某处
答案 4 :(得分:0)
import java.util.Scanner; //import scanner class
public class FactorialCalculator
{
public static long calculator(int num)
{
long fact = 1;
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;
//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();
fact = FactorialCalculator.calculator(num);
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();
}
}
}
答案 5 :(得分:0)
从这开始:
fact = FactorialCalculator.calculator(fact, num)
你应该注意到程序会第一次计算阶乘权,然后它会从第二次开始失败。修复这个bug是你的工作。