CaptainMark
January 24th, 2011, 12:03 AM
Just working through a basic beginner program in java, just read about the exception handling syntax and cant figure out what i seem to be doing wrong, ive written this try/catch statement in
try { //Try to capture data
System.out.print("\nPlease enter you meal price: £");
value = reader.readLine(); // Capture meal price
mealPrice = Float.parseFloat(value); // Parse string to float
System.out.print("\nPlease enter the amount you want to tip in %: ");
value = reader.readLine(); // Capture Tip percentage
tipPercent = Float.parseFloat(value); // Parse string to float
} // End try
catch (IOException ioe) { // Handle exceptions
System.out.println("Input Output Error!");
} // End catch
But when i run the program and input some text instead of a number i dont get the message ive typed but a program error message
mark@mark-desktop:~/Documents/programming/java/java_programming_for_absolute_beginners/chapter_2$ java userInput
----------------------------------------------
£££ Tip Calculator £££
Please enter you meal price: £example
Exception in thread "main" java.lang.NumberFormatException: For input string: "example"
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1242)
at java.lang.Float.parseFloat(Float.java:439)
at userInput.main(userInput.java:33)I dont understand why, ive copied the syntax as it should be from the book i have
It compiles and runs no problem, and just to be sure, i ran the version that came with the book and it does the same
Any suggestions?
try { //Try to capture data
System.out.print("\nPlease enter you meal price: £");
value = reader.readLine(); // Capture meal price
mealPrice = Float.parseFloat(value); // Parse string to float
System.out.print("\nPlease enter the amount you want to tip in %: ");
value = reader.readLine(); // Capture Tip percentage
tipPercent = Float.parseFloat(value); // Parse string to float
} // End try
catch (IOException ioe) { // Handle exceptions
System.out.println("Input Output Error!");
} // End catch
But when i run the program and input some text instead of a number i dont get the message ive typed but a program error message
mark@mark-desktop:~/Documents/programming/java/java_programming_for_absolute_beginners/chapter_2$ java userInput
----------------------------------------------
£££ Tip Calculator £££
Please enter you meal price: £example
Exception in thread "main" java.lang.NumberFormatException: For input string: "example"
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1242)
at java.lang.Float.parseFloat(Float.java:439)
at userInput.main(userInput.java:33)I dont understand why, ive copied the syntax as it should be from the book i have
It compiles and runs no problem, and just to be sure, i ran the version that came with the book and it does the same
Any suggestions?