你们可以帮我解决我的java程序吗?我目前正在制作货币转换器,我需要做一个选项,用户可以输入英镑金额并点击转换它进行转换,然后可以选择输入自己的汇率进行计算和转换时单击然后它将使用用户输入的汇率而不是我设置的汇率。这是我到目前为止将英镑转换为美元的代码,该程序在我输入金额并且自己也输入汇率时起作用,但是将输入汇率框留空并使用固定汇率设置的选项带来了转换时出错:
public class cConverter extends javax.swing.JFrame {
double GBPtoUSD = 1.288;
//this is the constant exchange rate for GBP to USD.
private void BtnConvertActionPerformed(java.awt.event.ActionEvent evt) {
double ConvertFromGBP = Double.parseDouble(InputFrom.getText());
double GetExchange = Double.parseDouble(ExchangeRateFrom.getText());
/* Input from is where the user inputs the GBP amount they want converted.
ExchangeRateFrom is the optional exchange rate box where the user inputs an
updated exchange rate if the constant one is out of date. */
if (CurrencyTop.getSelectedItem().equals("USD")){
String cGBPtoUSD = String.format("%.2f", ConvertFromGBP * GBPtoUSD);
ConvertedFrom.setText(cGBPtoUSD);
}
else if (CurrencyTop.getSelectedItem().equals("USD")) {
String uGBPtoUSD = String.format("%.2f", GetExchange * ConvertFromGBP);
ConvertedFrom.setText(uGBPtoUSD);
}
/* CurrencyTop is a combo box containing the currencies to convert to.
ConvertedFrom is the calculation output label. */
在没有输入汇率的情况下进行转换时出现错误异常(当没有输入此框时,应使用GBPtoUSD加倍):
线程中的异常" AWT-EventQueue-0" java.lang.NumberFormatException:empty String
答案 0 :(得分:0)
你的异常可能发生在这里:
double GetExchange = Double.parseDouble(ExchangeRateFrom.getText());
您应该检查空输入(也在InputFrom.getText()上):
String input = ExchangeRateFrom.getText();
if(null == input || input.isEmpty()) {
GetExchange = GBPtoUSD;
}
else {
try {
GetExchange = Double.parseDouble(input);
}
catch(Exception ex) {
// use default or do something else on invalid input
GetExchange = GBPtoUSD;
}
}
然后使用GetExchange在一个if-block中进行转换:
if (CurrencyTop.getSelectedItem().equals("USD")){
String uGBPtoUSD = String.format("%.2f", GetExchange * ConvertFromGBP);
ConvertedFrom.setText(uGBPtoUSD);
}