你能在if语句中有两个条件吗?

Maa*_*asi -2 java conditional if-statement conditional-statements

我是java编码的初学者,所以我经常浏览以找到具有我基本知识的初学者项目.我最近正在创建一个聊天程序,用户将与我的计算机聊天.这是代码的一部分,因为我不需要显示整个代码:

 System.out.println("Hello, what's our name? My name is " + answer4);
        String a = scanner1.nextLine();
        System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
        String b = scanner2.nextLine();
        **if (b.equals("good"))** {
            System.out.println("Thank goodness");
        } else **if (b.equals("it was good"))** {
            System.out.println("Thank goodness");
        } else **if (b.equals("bad"))** {
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }
        else **if (b.equals("it was bad"))**{
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }

        if(age<18){System.out.println("How was school?");}
        else if (age>=18){System.out.println("How was work?");}
Run Code Online (Sandbox Code Playgroud)

if语句的条件是粗体.第一个和第二个是相似的,第三个和第四个也是如此.我认为有可能让它们成为现实,但事实并非如此:

 if (b.equals("good"),b.equals("it was good")) {
            System.out.println("Thank goodness");
        }  else if (b.equals("bad"),(b.equals("it was bad"))) {
            System.out.println("Why was it bad?");
            String c = scanner3.nextLine();
            System.out.println("Don't worry, everything will be ok, ok?");
            String d= scanner10.nextLine();
        }
Run Code Online (Sandbox Code Playgroud)

有人可以帮我纠正吗?我真的很感激!

Zab*_*uza 10

你可以logical operators用来组合你的boolean expressions.

  • &&是一个逻辑(两个条件都需要是true)
  • ||是逻辑的(至少需要一个条件true)
  • ^是一个xor(只需要一个条件true)
  • (==按身份比较对象)

例如:

if (firstCondition && (secondCondition || thirdCondition)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

还有按位运算符:

  • &是一个有点
  • |是一个按位
  • ^是一个xor

它们主要用于操作时bits and bytes.但是还有另外一个区别,让我们再看看这个表达式:

firstCondition && (secondCondition || thirdCondition)
Run Code Online (Sandbox Code Playgroud)

如果使用逻辑运算符并firstCondition进行求值,falseJava 不会计算第二个或第三个条件,因为已知整个逻辑表达式的结果false.但是,如果您使用按位运算符,则Java不会停止并继续计算所有内容:

firstCondition & (secondCondition | thirdCondition)
Run Code Online (Sandbox Code Playgroud)