看一下下面的java代码。
String Remark="";
boolean Paid, PartiallyPaid, NotPaid;
if(Paid=true) {Remark="Paid";}
if(PartiallyPaid=true) {Remark="Partially Paid";}
if(NotPaid=true) {Remark="Not Paid";}
这里的 boolean 值由单选按钮确定。我想如上所述分配字符串“Remark”。但它总是只给出最后的分配值(作为“未支付”)。有人解释一下为什么会发生这种情况吗?
最佳答案
使用 ==
而不是 =
进行比较。
==
用于比较两个值是否相等
=
用于将一个值分配给另一个值
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid==true) {Remark="Paid";}
if(PartiallyPaid==true) {Remark="Partially Paid";}
if(NotPaid==true) {Remark="Not Paid";}
正如unholysampler所指出的
对于 boolean 值,您不必显式检查是否相等。以下就可以了
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid) {Remark="Paid";}
if(PartiallyPaid) {Remark="Partially Paid";}
if(NotPaid) {Remark="Not Paid";}
关于java - Java 中 "if statement"的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25206127/