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. Te catch block forces the number to 0 and displays an appropriate error message. Following the catch block, display the number. Save the fle as TryToParseDouble.java.

Respuesta :

Answer:

  1. import java.util.Scanner;
  2. public class TryToParseDouble {
  3.    public static void main(String[] args) {
  4.        Scanner input = new Scanner(System.in);
  5.        double num;
  6.        try{
  7.            System.out.print("Input a number: ");
  8.            num = Double.parseDouble(input.nextLine());
  9.        }catch(NumberFormatException e){
  10.            num = 0;
  11.            System.out.println("Invalid input! It should be a number in double type");
  12.        }
  13.        System.out.println(num);
  14.    }
  15. }

Explanation:

Firstly, create a Scanner object to get user input (Line 5).

Next, create a try block and prompt user to input a number and use Double.parseDouble() method to convert the input to double type in the block (Line 8-10).

Next, create a catch block to catch a NumberFormatException. In the Catch block, set the num to zero and then print out a message to inform user about the invalid input (Line 12-14).

Lastly, display the number (Line 16).

Catching exceptions are used to prevent programs from crashing, when the program encounters errors.

The application in Java where comments are used to explain each line is as follows:

import java.util.*;

public class Main {

  public static void main(String[] args) {

      //This creates a scanner object

      Scanner scr = new Scanner(System.in);

      //This declares doubleNum as double

      double doubleNum;

      //This opens the try block

      try{

          //This prompts the user for input

          System.out.print("Number: ");

          //This gets input using Double.parseDouble() method

          doubleNum = Double.parseDouble(scr.nextLine());

      }

      //This opens the catch block

      catch(NumberFormatException e){

          //This sets doubleNum to 0

          doubleNum = 0;

          //This prints the Exception

          System.out.println("Invalid input!");

      }

      //This prints the number

      System.out.println(doubleNum);

  }

}

Read more about exceptions at:

https://brainly.com/question/18497347