1

我目前是入门级 Java 课程的学生,我们的教授正在让我们制作各种金融计算器。无论如何,我想比我已经知道的要领先一步,这样如果用户要在我在输入对话框中询问他们的值之前输入一个 $ 符号,它就不会抛出整个程序。目前,如果我输入 10 甚至 10.00 的值,我的程序不会介意。但是一个典型的用户可能会输入 10.00 美元。

我相信它抛出程序的原因是因为我在输入一个字符串来表示它之后解析了双精度。而且我不相信我可以解析货币符号。您可能会在我的源代码中注意到我输入了一个货币包,但我真的不知道如何实现它。

我的代码....到目前为止:

  import javax.swing.JOptionPane;
  import java.text.NumberFormat;
  class Program1 {
  public static void main(String[] args) {

  String WageInput = JOptionPane.showInputDialog("Enter the numeral representing your     hourly wage");
  double HourlyWage = Double.parseDouble(WageInput);
  String HoursInput = JOptionPane.showInputDialog("How many hours do you work a week");
  double HoursAWeek = Double.parseDouble(WageInput);
  
    }
}

我的教授的项目描述,注:

使用JOptionPane该类,您的 Java 应用程序应询问用户每小时工资率、每周工作小时数,然后计算年薪。

然后它应该要求用户输入期望的加薪百分比,并在收到加薪的情况下计算年薪,并列出起始年薪和年薪之间的差额以及百分比加薪。

4

3 回答 3

1

如果您想要一种强大的方法来解析货币值,您可以使用NumberFormat执行以下操作:

final String wageInput = JOptionPane.showInputDialog("Enter the numeral representing your hourly wage");

// Prepare a "container" that will be able to parse a currency value in current locale
// (change the `Locale` if needed)
NumberFormat nf_US = NumberFormat.getCurrencyInstance(Locale.US);
try {
    // try to parse a valid currency value for current locale
    final double wage = nf_US.parse(wageInput).doubleValue();
} catch(NumberFormatException nfe) {
    // if it fails to parse --> Invalid currency --> tell the user
    JOptionPane.showMessageDialog(null, "Invalid currency");
}

这基本上强制输入是程序当前语言环境中的有效货币,Java 能够自行决定它是否有效。

于 2013-09-07T01:47:00.517 回答
1

你有几个选择。最重要的警告是,您将无法使用默认选项窗格来执行此操作。您将不得不提供自己的文本字段来满足您自己的需求...

您可以尝试使用JSpinner. 这有一个很好的功能,即能够解析用户输入并以Object您要求的格式返回 a (即double),如果输入有效。它不会将输入验证为用户类型,因此这仍然允许用户输入他们想要的任何内容,但是当您要求输入值时,该字段将拒绝它......

在此处输入图像描述

JSpinner currency = new JSpinner();
currency.setModel(new javax.swing.SpinnerNumberModel());
currency.setEditor(new javax.swing.JSpinner.NumberEditor(currency, "00.00"));
JLabel label = new JLabel("Enter the numeral representing your hourly wage");
JPanel panel = new JPanel();
panel.add(label);
panel.add(filteredField);

JOptionPane.showMessageDialog(null, panel, "Hourly Rate", JOptionPane.QUESTION_MESSAGE);

System.out.println("You entered " + currency.getValue());

另一种选择是使用DocumentFilter. 这具有在用户键入时处理用户输入的好处。对话框关闭后,您仍然需要解析输入,但您至少可以保证可能的格式文本将在...

有关更多详细信息,请参阅文本组件功能文档过滤器...

于 2013-09-07T03:18:56.160 回答
1

您对变量名的命名约定不正确;你应该使用骆驼套管。除此之外,您可以检查输入是否以 $ 开头,如果是,您可以修剪它:

    final String wageInput = JOptionPane.showInputDialog("Enter the numeral representing your     hourly wage");
    final double wage = Double.parseDouble(wageInput.startsWith("$") ? wageInput.substring(1) : wageInput);
于 2013-09-07T01:13:04.713 回答