我的程序的目标很简单,向用户询问阶乘乘数。将该值作为整数传递给另一个类,使用构造函数(这样做的对象)。使用 getter setter 和 factorial 方法,最终将结果返回给要打印的 main 方法。但是,当我尝试运行程序时出现错误:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
我尝试将方法类型更改为 void,以尝试使只有一种方法具有返回值(getter 类型)。但是,这会导致更多问题,因为它指出 (*) 不能用于 void 方法。任何输入将不胜感激。这是我的课程:
主程序
import java.io.*;
public class RecursionIntroRev {
Numbers p = new Numbers();
public void main (String [] args) throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
String input;
while(true) {
try{
System.out.println("Hello and welcome to the program!");
System.out.println("Please enter a 'n' value (Factorial Multiple you wish to use)");
input = myInput.readLine();
int n = Integer.parseInt(input);
p.setNum(n);
}
catch (Exception e) {
System.out.println("Enter valid input!");
}
System.out.println("The Factorial value is " + p.getNum());
}
}
}
Numbers 类(Setter、getter、Factorial 方法)
import java.io.*;
public class Numbers {
private int x;
public void setNum(int n) throws IOException {
x = n; // setter
}
public int Factorial(int x) {
// factorial method...
if(x > 1) {
x = x *Factorial(x-1);
}
return x;
}
public int getNum() {
return x; //getter
}
}