import java.util.*;
//Creates a program which allows the user to find the factorial of a number
public class forLoop {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want the factorial from: ");
int number = input.nextInt(); // user input
input.close();
int result_2 = getFactorial(number); //initializes getFactorial method
System.out.println("The factorial of " + number + " is " + result); //prints results
}
public static int getFactorial (int num1) {
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
return result; // returns results (here is the problem)
}
}
6 に答える
コンパイラは、ループが少なくとも 1 回は実行されると想定できません。これはresult
、 が割り当てられるために必要な条件です。
の宣言をresult
次のように変更して、問題を修正します。
int result = 1;
これはコードのコンパイルに役立ちますが、階乗を計算する際の論理エラーは修正されません。現在、ループ条件が間違っているため、ループが無期限に実行されます。
1
からまでの数値を乗算する必要がありますnum1
。このエラーを修正するには、ループ条件をtimes >= 1
の代わりにso に変更しtimes <= 1
、ループ本体をに変更します。result *= times
この変数を初期化する必要があります。
int result;
このような:
int result = 0; //Which ever intial value you want
コンパイラは、for ループが常に実行されることを確認できないためです。
関数の戻り値を に割り当てているためresult_2
、結果の代わりにそれを出力する必要があります
試す
System.out.println("The factorial of " + number + " is " + result_2);
そして、それらを使用する前にローカル変数を初期化する必要があります
for ループの条件が正しくありません
それはあるべきです
for (int times = num1; times >= 1; times--)
{
result *= times; //this wil calculate right factorial
}
また、 for ループの前に結果を 1 に初期化します
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
このブロックがエラーの原因です。これが原因でループが一度も実行されない場合
回 <=1
条件Javaはここに印刷するものを持っていません
System.out.println("The factorial of " + number + " is " + result);
したがって、印刷するためのデフォルト値として機能する初期化が必要になります。したがって、解決策は交換することです
int result;
と
int result=1; // note that I am not initializing with 0 as that will cause every factorial to become zero.
代わりに、コードに別の間違いがあります
times <= 1
そのはず
times >= 1
あなたのコードは、おそらくこのエラーに対して一度も実行されません。