[英]Boolean if statement
public class Health
{
boolean dependency;
String insuranceOwner = "";
static final int basicHealthFee = 250;
static final int healthDiscount = 20;
public Health(boolean dependent, String insurance)
{
dependency = dependent;
insuranceOwner = insurance;
}
public double computeCost()
{
double healthFee;
if (dependency == true)
{
healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100.0));
}
else
{
healthFee = basicHealthFee;
}
return healthFee;
}
}
Health h34 = new Health(true, "Jim");
System.out.println("discount price: " + h34.computeCost());
當我輸入true作為構造函數的參數時,我的computeCost方法仍然運行塊,就好像依賴項是== false。 有什么理由嗎?
你是整數分裂的受害者。 20/100 == 0
,任何乘以的東西都是0.要解決這個問題,請將static final int
聲明更改為double。
static final double basicHealthFee = 250D;
static final double healthDiscount = 20D;
D
定義了雙字面量 。
您需要將basicHealthFee和healthDiscount定義為double
。 由於您已將它們定義為整數,因此您可以使用以下公式: healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100));
變成basicHealthFee - ( basicHealthFee * (20/100))
成為basicHealthFee - (basicHealthFee * 0)
- > basicHealthFee - 0
。
if語句從構造函數中獲取其值是正確的。
您的問題與布爾值無關。 這是由於整數的划分。 請按如下方式更改程序。 static final double healthDiscount = 20d; static final double basicHealthFee = 250d;
package com.stackoverflow.test;
public class Health {
boolean dependency;
String insuranceOwner = "";
static final double basicHealthFee = 250d;
static final double healthDiscount = 20d;
public Health(boolean dependent, String insurance) {
dependency = dependent;
insuranceOwner = insurance;
}
public double computeCost() {
double healthFee;
if (dependency == true) {
healthFee = basicHealthFee
- (basicHealthFee * (healthDiscount / 100.0d));
} else {
healthFee = basicHealthFee;
}
return healthFee;
}
public static void main(String args[]) {
Health h34 = new Health(true, "Jim");
System.out.println("discount price: " + h34.computeCost());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.