每当我运行程序而不传入usDollarAmount或取消程序时,我都会收到异常...我使用swing组件来接受用户输入。该程序工作正常。
请告诉我如何处理这个......谢谢
THE Currency CALCULATOR
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Currency.main(Currency.java:28)
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Currency{
public static void main(String[] args)
{
// declare and construct variables
double usDollarAmount, poundsAmount,eurosAmount,rublesAmount;
DecimalFormat twoDigits = new DecimalFormat("####.00");
//print prompts and get input
System.out.println("\tTHE Currency CALCULATOR");
//print prompts and get input
usDollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));
// calculations
poundsAmount = 0.64 * usDollarAmount;
eurosAmount = 0.91 * usDollarAmount ;
rublesAmount = 61.73 * usDollarAmount ;
// output
JOptionPane.showMessageDialog(null, "YOUR DOLLAR AMOUNT OF " + twoDigits.format(usDollarAmount) + " is equal to " + twoDigits.format(eurosAmount) + " euros" + " ," + twoDigits.format(poundsAmount) + " pounds" + " " + " and " + twoDigits.format(rublesAmount) + " rubles" );
System.exit(0);
}
}
答案 0 :(得分:0)
首先将输入分配给变量,然后进行空检查。如果不为null则执行解析
String input = JOptionPane.showInputDialog(null, "Enter your dollar amount:");
if(input != null && !input.trim().isEmpty())
usDollarAmount = Double.parseDouble();