将2个字符串相乘

时间:2013-01-28 18:55:59

标签: java string multiplication

我正试图将两个简单的字符串加在一起用于我的一类。该计划本身将根据用户输入的每小时费率和工作小时数显示总工资。我已经做了一些挖掘,但我发现的结果,似乎过于复杂,我想要实现的目标。当然,我是从C#转到Java,所以我承认存在差异。以下是我到目前为止的代码。

    String RoPString, hrswrkdString;

    double grosspay, netpay, whtax;

    //Rate of pay input dialog box.
    RoPString = JOptionPane.showInputDialog(null, "Enter employee's hourly rate", "Rate of Pay", JOptionPane.INFORMATION_MESSAGE);

    //Hours worked input dialog box.
    hrswrkdString = JOptionPane.showInputDialog(null, "Enter hours worked", "Hours Worked", JOptionPane.INFORMATION_MESSAGE);

    //Calculations
    grosspay = RoPString*hrswrkdString;

    //Summary of pay
    JOptionPane.showMessageDialog(null, "Gross Pay: $" + grosspay);

2 个答案:

答案 0 :(得分:4)

grosspay = RoPString*hrswrkdString;

您无法在*类型上应用String运算符。将String转换为double,然后转换*

示例:

  double ropdouble = Double.valueOf(RoPString);
  double hrswrkddouble = Double.valueOf(hrswrkdString);

注意:在命名变量时遵循Java命名约定(变量名以小写字母开头)。

答案 1 :(得分:1)

我认为您需要使用Double.parseDouble()String个对象转换为可用于乘法的对象。

String RoPString, hrswrkdString;
double grosspay, netpay, whtax;

//Rate of pay input dialog box.
RoPString = JOptionPane.showInputDialog(null, "Enter employee's hourly rate", "Rate of Pay", JOptionPane.INFORMATION_MESSAGE);

//Hours worked input dialog box.
hrswrkdString = JOptionPane.showInputDialog(null, "Enter hours worked", "Hours Worked", JOptionPane.INFORMATION_MESSAGE);

//Calculations
grosspay = Double.parseDouble(RoPString)*Double.parseDouble(hrswrkdString);

//Summary of pay
JOptionPane.showMessageDialog(null, "Gross Pay: $" + grosspay.toString());

}