Java 程序:检查三个布尔变量中有两个是否为 true

要理解此示例,您应了解以下Java编程主题


示例:检查三个布尔变量中有两个为真

// Java Program to check if 2 variables
// among the 3 variables are true

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    // create 3 boolean variables
    boolean first;
    boolean second;
    boolean third;
    boolean result;

    // get boolean input from the user
    Scanner input = new Scanner(System.in);
    System.out.print("Enter first boolean value: ");
    first = input.nextBoolean();

    System.out.print("Enter second boolean value: ");
    second = input.nextBoolean();

    System.out.print("Enter third boolean value: ");
    third = input.nextBoolean();

    // check if two are true
    if(first) {

      // if first is true
      // and one of the second and third is true
      // result will be true
      result = second || third;
    }
    else {

      // if first is false
      // both the second and third should be true
      // so result will be true
      result = second && third;
    }

    if(result) {
      System.out.println("Two boolean variables are true.");
    }
    else {
      System.out.println("Two boolean variables are not true.");
    }

    input.close();
  }

}

输出 1

Enter first boolean value: true
Enter second boolean value: false
Enter third boolean value: true
Two boolean variables are true.

输出 2

Enter first boolean value: false
Enter second boolean value: true
Enter third boolean value: false
Two boolean variables are not true.

在上面的示例中,我们有三个名为firstsecondthird的布尔变量。在这里,我们检查了这三个布尔变量中有两个是否为真。

我们使用if...else语句来检查两个布尔变量是否为真。

if(first) {
  result = second || third;
}
else {
  result = second && third;
}

在这里,我们可以使用三元运算符代替if...else语句。

result = first ? second || third : second && third;

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战