Introduction
In this lab, you will learn how to determine if a given string can be successfully converted into a double-precision floating-point number in Java. We will explore the process of attempting to parse a string using Double.parseDouble(), understand how to handle potential NumberFormatException errors that may occur if the string is not a valid numerical representation, and discuss methods for checking if a string adheres to a valid decimal format. By the end of this lab, you will be equipped with the knowledge to safely and effectively convert strings to doubles in your Java applications.
Attempt Parsing with Double.parseDouble()
In this step, we will learn how to convert a string representation of a number into a numerical type in Java. This is a common task when you receive input from a user or read data from a file, as input is often initially read as text (strings).
Java provides several ways to perform this conversion. One of the most common methods for converting a string to a double-precision floating-point number is using the Double.parseDouble() method.
Let's create a simple Java program to demonstrate this.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
import java.util.Scanner; public class HelloJava { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a decimal number: "); String userInput = scanner.nextLine(); // Attempt to parse the input string into a double double number = Double.parseDouble(userInput); System.out.println("You entered: " + number); scanner.close(); } }Let's look at the new parts of this code:
System.out.print("Enter a decimal number: ");: This line prompts the user to enter a decimal number.String userInput = scanner.nextLine();: This reads the user's input as a string and stores it in theuserInputvariable.double number = Double.parseDouble(userInput);: This is the core of this step.Double.parseDouble()takes theuserInputstring and attempts to convert it into adoublevalue. If the string can be successfully interpreted as a decimal number, the resultingdoublevalue is stored in thenumbervariable.System.out.println("You entered: " + number);: This line prints the parseddoublevalue back to the user.
Save the file (Ctrl+S or Cmd+S).
Now, compile the modified program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Then run:javac HelloJava.javaIf the compilation is successful, you will see no output.
Finally, run the program:
java HelloJavaThe program will prompt you to enter a decimal number. Type a valid decimal number, like
123.45, and press Enter.Enter a decimal number: 123.45 You entered: 123.45The program should successfully parse your input and print the number back to you.
In this step, you've successfully used Double.parseDouble() to convert a valid string representation of a decimal number into a double. However, what happens if the user enters something that is not a valid number? We will explore this in the next step.
Handle NumberFormatException
In the previous step, we saw how Double.parseDouble() works when the input string is a valid decimal number. But what happens if the user enters text that cannot be converted into a number? Let's try it.
Make sure you are in the
~/projectdirectory in the Terminal.Run the program again:
java HelloJavaWhen prompted to enter a decimal number, type something that is clearly not a number, like
helloorabc.Enter a decimal number: helloPress Enter. You will likely see a lot of red text in the Terminal. This is an error message, specifically a
NumberFormatException.Exception in thread "main" java.lang.NumberFormatException: For input string: "hello" at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2050) at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.base/java.lang.Double.parseDouble(Double.java:651) at HelloJava.main(HelloJava.java:10)This
NumberFormatExceptionoccurs because the string "hello" cannot be parsed into a validdoublevalue. When an exception like this happens and is not handled, the program crashes and stops executing.In real-world applications, you don't want your program to crash just because a user enters invalid input. You need a way to gracefully handle such errors. In Java, we use
try-catchblocks to handle exceptions.A
try-catchblock works like this:- The code that might cause an exception is placed inside the
tryblock. - If an exception occurs within the
tryblock, the code inside thecatchblock is executed. - If no exception occurs, the
catchblock is skipped.
- The code that might cause an exception is placed inside the
Let's modify our program to use a try-catch block to handle the NumberFormatException.
Open the
HelloJava.javafile in the WebIDE editor.Modify the code to wrap the
Double.parseDouble()call within atry-catchblock:import java.util.Scanner; public class HelloJava { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a decimal number: "); String userInput = scanner.nextLine(); try { // Attempt to parse the input string into a double double number = Double.parseDouble(userInput); System.out.println("You entered: " + number); } catch (NumberFormatException e) { // This code runs if a NumberFormatException occurs System.out.println("Invalid input. Please enter a valid decimal number."); } scanner.close(); } }In this updated code:
- The
Double.parseDouble(userInput);line is inside thetryblock. - The
catch (NumberFormatException e)block specifies that if aNumberFormatExceptionoccurs in thetryblock, the code inside thecatchblock should be executed. - Inside the
catchblock, we print a user-friendly error message instead of letting the program crash.
- The
Save the file (Ctrl+S or Cmd+S).
Compile the modified program:
javac HelloJava.javaRun the program again:
java HelloJavaWhen prompted, enter invalid input like
helloagain.Enter a decimal number: hello Invalid input. Please enter a valid decimal number.This time, instead of crashing, the program caught the
NumberFormatExceptionand printed the message from thecatchblock. This is a much better user experience!
You have now learned how to use try-catch blocks to handle exceptions like NumberFormatException, making your programs more robust and user-friendly.
Check for Valid Decimal Format
In the previous step, we successfully handled the NumberFormatException using a try-catch block. This prevents our program from crashing when the input is not a valid number. However, the current approach still attempts to parse the string and only catches the error after the parsing fails.
A more proactive approach is to check if the input string has a valid decimal format before attempting to parse it. This can be done using regular expressions or other validation techniques. For this lab, we will use a simple check within a loop to repeatedly ask the user for input until a valid decimal number is provided.
This approach combines the try-catch block with a loop to ensure we get valid input.
Open the
HelloJava.javafile in the WebIDE editor.Modify the code to include a loop that continues until valid input is received:
import java.util.Scanner; public class HelloJava { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double number = 0.0; // Initialize with a default value boolean validInput = false; // Flag to track valid input while (!validInput) { System.out.print("Enter a decimal number: "); String userInput = scanner.nextLine(); try { // Attempt to parse the input string into a double number = Double.parseDouble(userInput); validInput = true; // Set flag to true if parsing is successful } catch (NumberFormatException e) { // This code runs if a NumberFormatException occurs System.out.println("Invalid input. Please enter a valid decimal number."); } } System.out.println("You entered a valid number: " + number); scanner.close(); } }Let's look at the changes:
double number = 0.0;: We initialize thenumbervariable outside the loop.boolean validInput = false;: We introduce a boolean variablevalidInputto control the loop. It's initiallyfalse.while (!validInput): This creates awhileloop that continues as long asvalidInputisfalse.- Inside the
tryblock, ifDouble.parseDouble()is successful, we setvalidInputtotrue. This will cause the loop to terminate after the current iteration. - If a
NumberFormatExceptionoccurs, thecatchblock is executed,validInputremainsfalse, and the loop will continue, prompting the user for input again. - After the loop finishes (meaning
validInputistrue), we print a message confirming that valid input was received.
Save the file (Ctrl+S or Cmd+S).
Compile the modified program:
javac HelloJava.javaRun the program:
java HelloJavaNow, try entering invalid input first, then enter a valid decimal number.
Enter a decimal number: abc Invalid input. Please enter a valid decimal number. Enter a decimal number: 1.2.3 Invalid input. Please enter a valid decimal number. Enter a decimal number: 789.01 You entered a valid number: 789.01The program will keep asking for input until you provide a string that
Double.parseDouble()can successfully convert.
You have now implemented a basic input validation loop that ensures your program receives a valid decimal number from the user before proceeding. This is a fundamental pattern for handling user input in many applications.
Summary
In this lab, we learned how to check if a string can be converted to a double in Java. We started by attempting to parse a string into a double using the Double.parseDouble() method. This method is a common way to convert string representations of numbers to numerical types, particularly useful when handling user input or data read from files. We implemented a simple Java program that prompts the user for input, reads it as a string, and then uses Double.parseDouble() to convert it to a double, demonstrating the basic process of string-to-double conversion.



