Respuesta :
Answer:
- import java.util.Scanner;
- public class TryToParseDouble {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- double num;
- try{
- System.out.print("Input a number: ");
- num = Double.parseDouble(input.nextLine());
- }catch(NumberFormatException e){
- num = 0;
- System.out.println("Invalid input! It should be a number in double type");
- }
- System.out.println(num);
- }
- }
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