Results 1 to 3 of 3
Thread: Exception handling problem
- 04-17-2010, 02:54 PM #1
Member
- Join Date
- Feb 2010
- Posts
- 26
- Rep Power
- 0
Exception handling problem
Why in the world am I getting a continuous loop when I enter a character instead of a float variable when the program asks the user to enter a float value?
I created an exception to handle the incorrect data but it will not work correctly, why?
Java Code:import java.util.*; import java.io.*; public class FloatingNumbersDriver { public static void main(String[] args) { Scanner in = new Scanner(System.in); FloatingNumbers myValues = new FloatingNumbers(); final int MAX_ERRORS = 0; int errors = 0, totalValues = 0, count = 1; String answer; float value = 0, sum = 0; System.out.print("\nEnter the total amount of float values to sum up: "); totalValues = in.nextInt(); while(count <= totalValues){ try { System.out.print("\nEnter a floating-point value: "); value = in.nextFloat(); sum += value; count++; // increment total } catch(InputMismatchException e){ System.out.println(" Invalid input, must enter a float value"); errors++; } } } }
-
Don't forget to grab the end-of-line char with the Scanner object:
Java Code:import java.util.*; public class FloatingNumbersDriver { public static void main(String[] args) { Scanner in = new Scanner(System.in); int errors = 0, totalValues = 0, count = 1; float value = 0, sum = 0; System.out.print("\nEnter the total amount of float values to sum up: "); totalValues = in.nextInt(); in.nextLine(); while (count <= totalValues) { try { System.out.print("\nEnter a floating-point value: "); value = in.nextFloat(); in.nextLine(); sum += value; count++; // increment total } catch (InputMismatchException e) { in.nextLine(); // *** this one especially! *** System.out.println(" Invalid input, must enter a float value"); errors++; } } } }
- 04-17-2010, 03:15 PM #3
Member
- Join Date
- Feb 2010
- Posts
- 26
- Rep Power
- 0
Similar Threads
-
Exception Handling help
By MZA in forum New To JavaReplies: 3Last Post: 02-10-2010, 09:23 AM -
Exception Handling Related
By dnzzn in forum New To JavaReplies: 9Last Post: 09-29-2009, 09:45 AM -
Exception handling and logging
By jurka in forum New To JavaReplies: 8Last Post: 09-03-2008, 07:07 PM -
Problem with JSP exception handling page
By sidster in forum JavaServer Pages (JSP) and JSTLReplies: 2Last Post: 06-19-2008, 07:28 PM -
Exception Handling...
By focus_nitin in forum New To JavaReplies: 1Last Post: 02-16-2008, 03:13 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks