How do I incorporate 2 catch statements for a IllegalArgumentExceptions in a factorials program?
Can you embed a if else statement in a catch block?
[code]
import java.util.Scanner;
public class Factorials
{
public static void main(String[] args)
{ try
{
String keepGoing = "y";
Scanner scan = new Scanner(System.in);
while (keepGoing.equals("y") || keepGoing.equals("Y"))
{
System.out.print("Enter an integer: ");
int val = scan.nextInt();
System.out.println("Factorial(" + val + ") = "
+ MathUtils.factorial(val));
System.out.print("Another factorial? (y/n) ");
keepGoing = scan.next();
}
}
catch (IllegalArgumentException ex)
{
System.out.println("Integer must be greater than 0");
}
catch (IllegalArgumentException ex)
{
System.out.println ("Integer must be less than 17");
}
}
}[/code]
[code]public class MathUtils
{
//-------------------------------------------------------------
// Returns the factorial of the argument given
//-------------------------------------------------------------
public static int factorial(int n) {
if (n < 0)
throw new IllegalArgumentException("Integer must be greater than 0");
else if (n > 16)
throw new IllegalArgumentException("Integer must less than 17");
{
int fac = 1;
for (int i=n; i>0; i--)
fac *= i;
return fac;
}
}
}[/code]