Results 1 to 4 of 4
Thread: string to float
- 02-02-2010, 07:59 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 10
- Rep Power
- 0
- 02-02-2010, 08:07 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
- 02-02-2010, 08:37 AM #3
Member
- Join Date
- Jan 2010
- Posts
- 10
- Rep Power
- 0
Oh, damn how silly is me....now I see, just too much C, I expected it to return 0...
hmm so how can I verify is string really a float? Such exceptions are annoying since they seem to stop whole function...
- 02-02-2010, 09:23 AM #4
Member
- Join Date
- Nov 2007
- Location
- New Zealand
- Posts
- 36
- Rep Power
- 0
Exceptions don't need to stop a function ("method" in java terminology).
Most exceptions can be recovered from.
Infact, they let you write cleaner code because you aren't inserting little checks and thus the purpose of a code block is clearer. Instead you can wrap problem code in a "try catch" block and handle the exceptions at the end.
I have included a code sniplet the demonstrates forcing the user to input a valid float. If the float is invalid, the user is hassled until they do enter a correct value.
Check out: Lesson: Exceptions (The Java™ Tutorials > Essential Classes) for details on exceptions.Java Code:import java.io.Console; class TestFloat { public static void main(String[] args) { // Get console object to read from console... Console cons; if ((cons = System.console()) == null){ System.out.println("Can't access console, closing program"); System.exit(1); } // Prompt user for a valid float, repeat until a valid float is entered String line; float f; while(true) { // Prompt user for float System.out.print("Please enter a valid float: "); // Read in user input as string line = cons.readLine(); // Wrap conversion code in a try catch block to handle the exception try { // Try convert String to float (may throw exception) f = Float.valueOf(line); // Exit while loop if an exception is not thrown break; } catch(NumberFormatException e) { // An exception was thrown, inform user and repeat loop System.out.println("That is not a valid float"); } } // A valid float value was (eventually entered), display it System.out.println("Float value was: " + f); } }
Hope this helps :-)
Similar Threads
-
Working with float
By dardar in forum New To JavaReplies: 8Last Post: 01-27-2010, 08:29 PM -
Float vs. Double
By javanub in forum New To JavaReplies: 1Last Post: 11-23-2008, 12:11 PM -
String to Float
By durahman in forum New To JavaReplies: 2Last Post: 02-12-2008, 12:17 AM -
Float to String
By mew in forum New To JavaReplies: 4Last Post: 12-29-2007, 05:08 PM -
convert string to float
By miss_dot in forum NetBeansReplies: 1Last Post: 11-14-2007, 11:26 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks