这是我到目前为止的代码。
我需要将最后一个if语句转换为double
public static void main(String[] args) {
double skill = 0; double hours = 0; double overTime= 0.5; int insurance =0;
String[] choices = {"Medical Insurance", "Dental Insurance", "Long-Term Disability Insurance"};
double MedicalInsuranceCount = 32.50;
double DentalInsuranceCount = 20.00;
double LongTermDisabilityInsuranceCount = 10.00
if (skill >= 20.00 && skill <=22.00)
insurance = JOptionPane.showOptionDialog(
null // Center in window.// prompts the user to select a button
, "Types of Insurance options" // Message
, "Insurance option" // Title in titlebar
, JOptionPane.YES_NO_OPTION // Option type
, JOptionPane.PLAIN_MESSAGE // messageType
, null // Icon (none)
, choices // Button text as above.
, "None of your business" // Default button's label
);
switch (insurance)
{
case 0:
MedicalInsuranceCount++;
break;
case 1:
DentalInsuranceCount++;
break;
case 2:
LongTermDisabilityInsuranceCount++;
break;
default:
//... If we get here, something is wrong. Defensive programming.
JOptionPane.showMessageDialog(null, "Unexpected response " + insurance);
}
// this is where the problem is I think.
if(insurance == 0)
insurance = Math.round((float)MedicalInsuranceCount);
else if(insurance == 1)
insurance = Math.round((float)DentalInsuranceCount);
else if(insurance == 2)
insurance = Math.round((float)LongTermDisabilityInsuranceCount);
System.out.println(insurance);
}
}
香港专业教育学院尝试使用Double.PasreDouble,但失败了,Math.round(浮动)是唯一有效的方法
答案 0 :(得分:2)
您没有明确说明insurance
的类型,但<{1}}有两个不同的签名:
如果您的Math#round
变量被声明为insurance
,则您将无法为其分配int
(不兼容的类型)。
答案 1 :(得分:1)
您的代码显示的一个问题是您使用insurance
变量做了太多事情,包括保存逻辑数据 - 我们处理的是什么类型的保险和浮点数字数据 - 保险费用是多少。不要这样做。使用单独的变量来实现单独的功能。
此外,我有一种潜在的怀疑,认为你的问题不仅仅是数字问题的四舍五入,而是格式化数字问题的显示。如果是这样的话,那么更少关注数字四舍五入以及更多地显示正确格式化的输出。 NumberFormat类型的对象可以帮助您解决此问题。例如......
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Foo5 {
public static void main(String[] args) {
double insurance = 32.50;
NumberFormat decimalFormat = new DecimalFormat("0.00");
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
System.out.println("Insurance is: " + decimalFormat.format(insurance));
System.out.println("Insurance in dollars is: " + currencyFormat.format(insurance));
}
}
哪个输出:
Insurance is: 32.50
Insurance in dollars is: $32.50