对于if commercial
声明:
如果我为1500
输入usage
,则会打印出
Total amount due: 22.560.0
但它应该是22.5+60.0 (82.5)
。关于我做错了什么想法?
import java.util.Scanner;
public class UtilityBill {
public static void main(String[] args) {
// residential customer
final double RES_RATE = 0.052;
final double RES_FEE = 6;
// commercial customer
final int COM_LIMIT = 1000;
final double COM_RATE = 0.045;
final double COM_FEE = 60;
// industrial customer
final int IND_LIMIT = 5000;
final int IND_LIMIT_2 = 1000;
final int IND_LIMIT_3 = 3000;
final double IND_RATE_BELOW = 0.028;
final double IND_FEE_BELOW = 76;
final double IND_RATE_ABOVE = 0.03;
final double IND_FEE_ABOVE = 270;
// user input
Scanner kb = new Scanner(System.in);
System.out.println("Enter the type of use ('R', 'C', or 'I'): ");
char userType = kb.next().charAt(0); // should be R, C, or I
System.out.println("How much electricity do you use (in kwh)? ");
double usage = kb.nextDouble(); // usage amount in kwh
// if residential
if (userType == 'R')
System.out.println("Total amount due: " + (RES_RATE*usage)+RES_FEE);
// if commercial
if (userType == 'C')
if (usage <= COM_LIMIT)
System.out.println("Total amount due: " + COM_FEE);
else
System.out.println("Total amount due: " + ((usage-COM_LIMIT)*COM_RATE)+COM_FEE);
// if industrial
if (userType == 'I')
if (usage <= IND_LIMIT)
System.out.println("Total amount due: " + ((usage-IND_LIMIT_2)*IND_RATE_BELOW)+IND_FEE_BELOW);
else
System.out.println("Total amount due: " + ((usage-IND_LIMIT_3)*IND_RATE_ABOVE)+IND_FEE_ABOVE);
kb.close();
}
}
答案 0 :(得分:0)
您的问题有一个非常简单的解释。这完全取决于运营商的优先级。考虑一个简单的代码:
int a = 6;
int b = 7;
System.out.println("Sum up : " + a + b);
虽然"Sum up : "
是一个字符串而"+"
是Java中唯一重载的运算符,但能够将数字连接到字符串。
在这里,我们在这里有2个"+"
运算符,a + b
在"Sum up : "
+之后已经发生了,它将x和y视为字符串。输出将是:
Sum up : 67
现在考虑以下代码:
int a = 6;
int b = 7;
System.out.println("Sum up : " + (a + b));
此处括号()
具有更高的优先级,因此首先(a+b)
然后将结果打印为:
Sum up : 13
回到你的代码:
System.out.println("Total amount due: " + ((usage-COM_LIMIT)*COM_RATE)+COM_FEE);
现在考虑:
((usage-COM_LIMIT)*COM_RATE) -> a
COM_FEE -> b
表达式变为:
System.out.println("Total amount due: " + a + b);
这与我的第一个代码段类似。
因此,为了获得所需的结果,您需要添加括号并转换为第二个示例:
System.out.println("Total amount due: " + (((usage-COM_LIMIT)*COM_RATE)+COM_FEE));
如果您在理解方面有任何问题,请告诉我。