اخوتي الكرام في منتدى الفريق العربي
عند تطبيق هذا الكود لايجاد مضروب العدد يظهر استتناء نوعه StackOverflowError
ما هذا الاستثناء ؟؟؟ كيف يمكن التعامل معه
هذا هو الكود
import java.io.*;
public class FactorialMain
{
public static void main (String[ ] args)
{
final int MAX = 20; // because 21! > Long.MAX_VALUE
final int SENTINEL = -1;
final String PROMPT = "\nPlease enter a non-negative integer (at most " +
MAX + "), or " + SENTINEL + " to quit: ";
final String ERROR = "Error: the input must be a non-negative integer or " + SENTINEL;
final String MESSAGE = " factorial is ";
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
int n;
while (true)
{
try
{
System.out.print (PROMPT);
n = Integer.parseInt (reader.readLine());
if (n == SENTINEL)
break;
if (n > MAX)
throw new IllegalArgumentException();
System.out.println (n + MESSAGE + factorial (n));
} // try
catch (Exception e)
{
System.out.println (e);
} // catch
} // while
} // method main
/**
* Calculates the factorial of a non-negative integer, that is, the product of all
* integers between 1 and the given integer, inclusive. The worstTime(n) is O(n),
* where n is the given integer.
*
* @param n the non-negative integer whose factorial is calculated.
*
* @return the factorial of n
*
* @throws IllegalArgumentException if n is less than 0.
*
*/
public static long factorial (int n)
{
if (n < 0)
throw new IllegalArgumentException( );
if (n <= 1)
return 1;
return factorial (n+1)/(n+1);
} // method factori
} // class FactorialMainالخطا في هذا الجزء
return factorial(n+1)/(n+1);
كيف ممكن تصحيحه انا حاولت
اني اضع مكانه
public static long factorial (int n)
{
if (n < 0)
throw new IllegalArgumentException( );
if (n <= 1)
return 1;
return n*factorial(n-1)* factorial((n+1)/(n+1));
} // method factoriلكن لم تضيظ ل مضروب 2
...ممكن مساعده اعرف وين الخطا في المتود
public static long factorial (int n)
{
if (n < 0)
throw new IllegalArgumentException( );
if (n <= 1)
return 1;
return factorial(n+1)/(n+1);
} // method factori
