Results 1 to 4 of 4
Thread: Factorials help
- 04-05-2009, 11:20 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 8
- Rep Power
- 0
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:
Java 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()); } } } }
-
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):
and you want this:Java Code:while (...) { get int check if it's less than 0 get int check if it's greater than 16 }
Java Code:while (...) { get int check if it's less than 0 || greater than 16 }Last edited by Fubarable; 04-06-2009 at 12:07 AM.
- 04-06-2009, 01:49 AM #3
Member
- Join Date
- Mar 2009
- Posts
- 8
- Rep Power
- 0
Thank you, I figured that was what was going on.
-


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks