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.

Respuesta :

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3.    public static void main(String[] args) {
  4.        Scanner input = new Scanner(System.in);
  5.        String numStr = input.nextLine();
  6.        double num;
  7.        try{
  8.            num = Double.parseDouble(numStr);
  9.        }
  10.        catch(NumberFormatException e){
  11.            num = 0;
  12.            System.out.println("Value entered cannot be converted to a floating point number.");
  13.        }
  14.    }
  15. }

Explanation:

The solution code is written in Java.

Firstly, we create a Scanner object and prompt user to input a number (Line 5-6). Next, we create a try -catch block and place the parseDouble inside the try block. If the input is invalid (e.g. "abc"), a NumberFormatException error will be thrown and captured and set the num to 0 and display the error message (Line 11 - 13).