私のプログラムの目標は単純です。階乗乗数をユーザーに尋ねます。その値を整数として別のクラスに渡し、コンストラクタ (オブジェクト) を使用します。ゲッター セッターと階乗メソッドを使用し、最終的に結果をメイン メソッドに返して出力します。ただし、プログラムを実行しようとすると、エラーが発生します。
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 に変更して、1 つのメソッドだけが戻り値 (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、Factial メソッド)
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
}
}