# Factorials help

• 04-06-2009, 12:20 AM
jhering1986
Factorials help
Ok so I have a Factorials file and I need to post an IllegalArgumentException error when the user types in a negative integer or an integer greater than 17 and I have it figured out, but sometimes the program doesn't function right. Sometimes when a negative integer is entered, it says 1 instead of IllegalArgumentException, but sometimes it works right. The same happens when something greater than 17 is entered. Here is my code:
Code:

package factorials;
// ****************************************************************
// Factorials.java
//
// Reads integers from the user and prints the factorial of each.
//
// ****************************************************************
import java.util.Scanner;
public class Factorials
{
public static void main(String[] args) throws IllegalArgumentException
{
Scanner sc = new Scanner(System.in);
char keepGoing = 'y';

while (keepGoing == 'y' || keepGoing == 'Y')
{
try {
System.out.print("Enter an integer: ");
int val = sc.nextInt();

if (val < 0) { throw new Exception("IllegalArgumentException"); }
sc.nextLine(); // consume extra newline
System.out.println("Factorial(" + val + ") = "
+ MathUtils.factorial(val));
System.out.print("Another factorial? (y/n) ");
keepGoing = sc.nextLine().charAt(0);
}
catch (Exception rtException)
{
System.err.println("Error: " + rtException.getMessage().toString());
}
try {
System.out.print("Enter an integer: ");
int val = sc.nextInt();

if (val > 16) { throw new Exception("IllegalArgumentException"); }
sc.nextLine(); // consume extra newline
System.out.println("Factorial(" + val + ") = "
+ MathUtils.factorial(val));
System.out.print("Another factorial? (y/n) ");
keepGoing = sc.nextLine().charAt(0);
}
catch (Exception rtException)
{
System.err.println("Error: " + rtException.getMessage().toString());
}

}
}
}

• 04-06-2009, 12:38 AM
Fubarable
You're program is only doing what you tell it to. Half the time when you enter a number it checks if it's > 16 and the other half the time it checks if it is < 0. You need to rewrite it so that it checks both all the time (hint: don't have two attempts to get the number within your while loop, have only one attempt).

In other words, you have this (pseudocode):
Code:

while (...)
{
get int
check if it's less than 0

get int
check if it's greater than 16
}

and you want this:
Code:

while (...)
{
get int
check if it's less than 0 || greater than 16
}

• 04-06-2009, 02:49 AM
jhering1986
Thank you, I figured that was what was going on.
• 04-06-2009, 02:50 AM
Fubarable