In: Computer Science
The Double.parseDouble() method requires a String argument, but it fails if the String cannot be converted to a floating-point number. Write an application in which you try accepting a double input from a user and catch a NumberFormatException if one is thrown. The catch block forces the number to 0 and displays Value entered cannot be converted to a floating-point number. Following the catch block, display the number.
import java.util.*;
public class TryToParseDouble {
public static void main(String[] args) {
// Write your code
here
}
}
import java.util.Scanner;
public class TryToParseDouble {
public static void main(String[] args) {
Scanner scan = new
Scanner(System.in);
double num;
try {
// Take input
and parse into double
System.out.print("Enter a number: ");
num =
Double.parseDouble(scan.nextLine());
} catch (NumberFormatException e)
{
// Set num to 0
and print error message
num = 0;
System.out.println("Value entered cannot be converted to a
floating-point number.");
}
// Print number
System.out.println("Value entered:
" + num);
}
}
OUTPUT