目錄
引用
其他文章:
【C++演示】編程語言的true、false和1、0之間的相互轉化
【C++】C++ true和false代碼演示
true、false和1、0轉化原理
Boolean轉化為數字
false為 0,true為 1
數字轉化為Boolean
0 為 false; 非 0 為true
java本身不支持直接強轉
一、Boolean轉化為數字——false為 0,true為 1
唯一方法:三目語句
int myInt = myBoolean ? 1 : 0;
示例代碼:
boolean myBoolean = true;
int myInt = myBoolean ? 1 : 0;
System.out.println(myInt); //輸出1
myBoolean = false;
myInt = myBoolean ? 1 : 0;
System.out.println(myInt); //輸出0
二、數字轉化為Boolean——0 為 false; 非 0 為true
方法一:
boolean myBoolean = myInt != 0;
示例代碼:
int myInt= 2;
boolean myBoolean = myInt!= 0;
System.out.println(myBoolean); //輸出為true
myInt= 0;
myBoolean = myInt!= 0;
System.out.println(myBoolean); //輸出為false
方法二:三目語句
int a = 1; //帶轉化int整數
boolean result = (a==0)?false:true; //轉化語句
示例代碼:
int myInt = 2; //被轉化int整數
boolean myBoolean = (myInt == 0) ? false : true; //轉化語句
System.out.println(myBoolean); //輸出為true
myInt = 0; //被轉化int整數
myBoolean = (myInt == 0) ? false : true; //轉化語句
System.out.println(myBoolean); //輸出為true