📜  Java程序将布尔值转换为整数

📅  最后修改于: 2022-05-13 01:55:39.689000             🧑  作者: Mango

Java程序将布尔值转换为整数

给定一个布尔值,任务是将此布尔值转换为Java中的整数值。

例子:

Input: boolean = true
Output: 1

Input: boolean = false
Output: 0

方法:

  • 获取要转换的布尔值。
  • 检查布尔值是真还是假
  • 如果布尔值为真,则将整数值设置为 1。
  • 否则,如果布尔值为 false,则将整数值设置为 0。

下面是上述方法的实现:

示例 1:当布尔值为真时

// Java Program to convert boolean to integer
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // The boolean value
        boolean boolValue = true;
  
        // The expected integer value
        int intValue;
  
        // Check if it's true or false
        if (boolValue) {
            intValue = 1;
        }
        else {
            intValue = 0;
        }
  
        // Print the expected integer value
        System.out.println(
            boolValue
            + " after converting into integer = "
            + intValue);
    }
}
输出:
true after converting into integer = 1

示例 2:当布尔值为 false 时

// Java Program to convert boolean to integer
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // The boolean value
        boolean boolValue = false;
  
        // The expected integer value
        int intValue;
  
        // Check if it's true or false
        if (boolValue) {
            intValue = 1;
        }
        else {
            intValue = 0;
        }
  
        // Print the expected integer value
        System.out.println(
            boolValue
            + " after converting into integer = "
            + intValue);
    }
}
输出:
false after converting into integer = 0