我可以在Java中将布尔值转换为另一种数据类型吗

我可以在Java中将布尔值转换为另一种数据类型吗,java,type-conversion,Java,Type Conversion,我有以下代码: public class MyFirstJavaProgram { public static void main(String []args) { boolean b = true; int x = b; System.out.println(x); } } 正如标题所说,我可以使用Java将布尔类型转换为另一种数据类型(在上面的示例中,char)吗?您不能直接进行转换,但可以通过以下

我有以下代码:

public class MyFirstJavaProgram {
        public static void main(String []args) { 
          boolean b = true; 
          int x = b; 
          System.out.println(x);
    }
} 

正如标题所说,我可以使用Java将布尔类型转换为另一种数据类型(在上面的示例中,
char
)吗?

您不能直接进行转换,但可以通过以下方式进行转换:

int myIntBool = (someBoolean) ? 1 : 0;
此外,您还可以使用

不,你不能

如果您正在寻找一种单线解决方案来设置
int
,则可以使用三元运算,例如:

int x = b ? 1 : 0;

你可以做
intx=b吗?1 : 0;

三值运算将产生结果

int y = booleanvalue ? 1: 0;

布尔值到整数

int convertedInt=0;

if(booleanToConvert)
  convertedInt=1;
布尔到字符

char convertedChar='';

if(booleanToConvert)
  convertedChae='Y';
else
  convertedChae='N';

您不能直接转换,但可以手动转换:

int x = b ? 1 : 0; //sets x to 1 if b is true, 0 otherwise

现在的问题是为什么要这样做?

char c=Boolean.parseBoolean(“true”)?'1' : '0'; 将c设置为1。 不太确定这是否是您想要的。

否 你使用三元运算

          int X = value ? 1: 0;

布尔值到整数:

return booleanValue ? 1 : 0;
return booleanValue ? 'Y' : 'N';
return booleanValue ? "YES" : "NO";
布尔到字符:

return booleanValue ? 1 : 0;
return booleanValue ? 'Y' : 'N';
return booleanValue ? "YES" : "NO";
布尔到字符串:

return booleanValue ? 1 : 0;
return booleanValue ? 'Y' : 'N';
return booleanValue ? "YES" : "NO";

依此类推……

No.。如果true将int设置为1,则使用条件语句,否则为0。Java是一种强类型语言,因此答案肯定是不可能重复的