【问题标题】:Can I convert boolean into another data type in Java我可以在 Java 中将布尔值转换为另一种数据类型吗
【发布时间】:2014-08-13 07:48:36
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

  • 否...使用条件语句 if true set int to 1 else 0.
  • Java 是一种强类型语言,所以这个问题的答案肯定是 NO

标签: java type-conversion


【解决方案1】:

不,你不能。

如果您正在寻找设置int 的单行解决方案,您可以使用三元运算,例如:

int x = b ? 1 : 0;

【讨论】:

    【解决方案2】:

    你可以int x = b ? 1 : 0;

    【讨论】:

      【解决方案3】:

      你不能直接这样做,但是你可以这样做:

      int myIntBool = (someBoolean) ? 1 : 0;
      

      另外,您可以使用BooleanUtils from Apache

      BooleanUtils.toInteger(true)  = 1
      BooleanUtils.toInteger(false) = 0
      

      【讨论】:

        【解决方案4】:

        没有 你用三元运算

                  int X = value ? 1: 0;
        

        【讨论】:

          【解决方案5】:

          三元运算会产生结果

          int y = booleanvalue ? 1: 0;
          

          【讨论】:

            【解决方案6】:

            布尔转 int

            int convertedInt=0;
            
            if(booleanToConvert)
              convertedInt=1;
            

            布尔转字符

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

            【讨论】:

              【解决方案7】:

              您不能直接转换,而是像这样手动转换:

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

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

              【讨论】:

                【解决方案8】:

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

                【讨论】:

                  【解决方案9】:

                  布尔转 int:

                  return booleanValue ? 1 : 0;
                  

                  布尔到字符:

                  return booleanValue ? 'Y' : 'N';
                  

                  布尔转字符串:

                  return booleanValue ? "YES" : "NO";
                  

                  等等……

                  【讨论】:

                    猜你喜欢
                    • 2011-01-28
                    • 2010-09-18
                    • 1970-01-01
                    • 1970-01-01
                    • 2023-01-04
                    • 1970-01-01
                    • 2020-05-27
                    • 1970-01-01
                    • 2023-02-07
                    相关资源
                    最近更新 更多