【问题标题】:Multiplying text field with combo box Netbeans将文本字段与组合框 Netbeans 相乘
【发布时间】:2016-04-17 23:23:54
【问题描述】:

我对 java 还很陌生,我想知道如何将用户在文本框中输入的数字乘以他们在组合框中选择的数字。 到目前为止我有这个:

 int Cost = Integer.parseInt(txtCost.getText());
   int TipCost;

   int Tip = Integer.parseInt((String)cboTip.getSelectedItem()); 

   TipCost = Cost*(Tip/100);
   TipCost = Math.round(TipCost);
   TipCost = TipCost/100;

我现在得到的只是0。

【问题讨论】:

  • 你用什么数字测试它?你不应该使用像double 这样的浮点数而不是int 吗?否则小数点后的所有内容都将被删除。
  • 您的组合框中有哪些选项?
  • 我有 5、10、15、20

标签: java netbeans int multiplication


【解决方案1】:

您的TipCost 必须是double 类型才能生成带小数点的数字。

此外,您的计算受到整数除法的影响,它忽略了余数。整数除以 100 的计算最好使用大于 100 的整数,否则结果将始终为 0。

你也有一些逻辑错误。以下是您应该如何修复代码:

int Cost = Integer.parseInt(txtCost.getText());
int Tip = Integer.parseInt(cboTip.getSelectedItem().toString()); 

double TipCost = Cost*Tip/100.0; // get the tip cost, 100.0 avoids integer division
TipCost = Math.round(TipCost*100)/100.0; // round to 2 decimal places

【讨论】:

  • 你可以通过double TipCost = Math.round(Cost*Tip)/100.0;进一步简化
  • 非常感谢!
【解决方案2】:

尝试在所选项目上调用toString() 方法,而不是强制转换所选值,如下所示:

int Tip = Integer.parseInt(cboTip.getSelectedItem().toString());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多