2 catch statements for an IllegalArgumentException. - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

2 catch statements for an IllegalArgumentException.

UNF_StephUNF_Steph Posts: 13Member
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]
Sign In or Register to comment.