12.6 The Double.parseDouble() method requires a String argument, but it fails if
ID: 3768934 • Letter: 1
Question
12.6 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 an appropriate error message. Following the catch block, display the number. Save the file as TryToParseDouble.java. Need code in HTML/JavaScript to run in Internet explorer to test.
Explanation / Answer
import javax.swing.*;
public class TryToParseDouble
{
public static void main(String[] args)
{
double parseDouble;
String inputString;
double result = 0;
try
{
inputString = JOptionPane.showInputDialog(null,
"Enter input");
parseDouble = Double.parseDouble(inputString);
}
catch(Exception e)
{
result=0;
JOptionPane.showMessageDialog(null, e.getMessage());
}
JOptionPane.showMessageDialog(null, " Result is " + result);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.