将文本字段与组合框 Netbeans 相乘
Multiplying text field with combo box Netbeans
我是 java 的新手,我想知道如何将用户在文本框中输入的数字乘以他们 select 在组合框中输入的数字。
到目前为止我有这个:
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。
尝试对所选项目调用 toString()
方法,而不是强制转换所选值,如下所示:
int Tip = Integer.parseInt(cboTip.getSelectedItem().toString());
您的 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
我是 java 的新手,我想知道如何将用户在文本框中输入的数字乘以他们 select 在组合框中输入的数字。 到目前为止我有这个:
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。
尝试对所选项目调用 toString()
方法,而不是强制转换所选值,如下所示:
int Tip = Integer.parseInt(cboTip.getSelectedItem().toString());
您的 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