[英]java - why does this code print the output it is supposed to print if a Boolean is true but the Boolean was declared to false?
我有以下代碼:
import java.util.*;
public class Test {
public static void main(String[] args) {
boolean b = false;
if (b=true)
System.out.println("one. b = false");
if (b)
System.out.println("two. b = false");
}
}
輸出為:
one. b = false
two. b = false
我將b設置為false,為什么為什么當b為true時打印語句?
您正在做作業,而不是比較
if (b=true)
你是說要用
if (b==true)
您需要使用。
if (b) {
System.out.println("one. b = true");
} else {
System.out.println("two. b = false");
}
如果需要檢查相等性,則需要使用“ ==”。 但是由於您使用的是布爾值,因此無需檢查相等性,而可以使用該值。
請檢查以下內容:
import java.util.*;
public class Test {
public static void main(String[] args) {
boolean b = false;
if (b==true)
System.out.println("one. b = " + Boolean.toString(b));
if (b)
System.out.println("two. b = " + Boolean.toString(b));
}
}
問題是在if語句b=true
您沒有進行比較。 我的意思是您不是在告訴java if b is equal to true
,實際上您在這里所做的是將true設置為b。 因此,您可以打印兩個System.out.print語句。 因為在兩種情況下該值均為true。
考慮到這一點:
在if語句中使用布爾值
if (b) { }
避免這種情況
if (b==true) {
}
不要嘗試(b=true)
而是(b==true)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.