Java if 语句中可以有两个条件吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44830259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:44:32  来源:igfitidea点击:

can you have two conditions in an if statement

javaif-statementconditional-statements

提问by Maame Yaa Twumasi

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:

我是编码初学者。我最近正在创建一个聊天程序,用户可以在其中与我的计算机聊天。这是代码的一部分:

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"))** {                //1
    System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** {  //2
    System.out.println("Thank goodness");
} else **if (b.equals("bad"))** {          //3
    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"))**{    //4
    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?");}

The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in ifstatement.

if 语句的条件为粗体(用 包围**)。在第一个和第二个条件的情况下,我希望我的应用程序做同样的事情。类似的第三和第四个条件。我认为有可能以某种方式将它们分组在if声明中。

I tried with below code but it doesn't compile:

我尝试使用以下代码,但无法编译:

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();
}

Can someone correct it for me?

有人可以为我纠正吗?

采纳答案by Zabuzard

You can use logical operatorsto combine your boolean expressions.

您可以使用logical operators将您的boolean expressions.

  • &&is a logical and(both conditions need to be true)
  • ||is a logical or(at least one condition needs to be true)
  • ^is a xor(exactly one condition needs to be true)
  • (==compares objects by identity)
  • &&是逻辑(两个条件都需要true
  • ||是逻辑(至少需要一个条件true
  • ^是一个异或(正好需要一个条件true
  • ==按身份比较对象)

For example:

例如:

if (firstCondition && (secondCondition || thirdCondition)) {
    ...
}

There are also bitwise operators:

还有按位运算符:

  • &is a bitwise and
  • |is a bitwise or
  • ^is a xor
  • &是按位
  • |是按位
  • ^异或

They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:

它们主要用于与bits and bytes. 然而还有另一个区别,让我们再看看这个表达式:

firstCondition && (secondCondition || thirdCondition)

If you use the logical operators and firstConditionevaluates to falsethen Javawill notcompute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Javawill not stop and continue computing everything:

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

firstCondition & (secondCondition | thirdCondition)

回答by Brondahl

You're looking for the "OR" operator - which is normally represented by a double pipe: ||

您正在寻找“OR”运算符 - 通常由双管道表示: ||

 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();
 }

回答by Brondahl

You can have two conditions if you use the double bars(||). They mean "Or". That means only ONEof your conditions has to be true for the loop to execute.

如果使用双杠 ( ||),则可以有两个条件。他们的意思是“或”。这意味着只有一个条件必须为真才能执行循环。

Something like this:

像这样的东西:

if(condition || otherCondition || anotherCondition) {
    //code here

If you want all of conditions to be true use &&. This means that ALLconditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.

如果您希望所有条件都为真,请使用&&. 这意味着所有条件都必须为真,循环才能执行。如果其中任何一项为假,则循环将不会执行。

Something like this:

像这样的东西:

if(condition && otherCondition && anotherCondition) {
    //code here

You can also group conditions, if you want certain pairs of them to be true. something like:

如果您希望某些条件对为真,您还可以对条件进行分组。就像是:

if(condition || (otherCondition && anotherCondition)) {
    //code here

回答by Simon Sirak

Here are some common symbols used in everyday language and their programming analogues:

以下是日常语言中使用的一些常见符号及其编程类似物:

  • "," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
  • "/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
  • ,”在日常用语中通常指“和”。因此,这将转换为&&Java 中的 AND 运算符 , 。
  • /”在日常用语中通常指“或”。因此,这将转换为||Java 中的 OR 运算符 , 。

"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ yin Java.

“XOR”只是“x || y 但两者不能同时为真”。这x ^ y在 Java 中转换为。

In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.

在您的代码中,您可能打算使用“或”(您只是使用了不正确的“不正确的解决方案”:p),因此您应该使用“||” 在第二个代码块中,使其与第一个代码块相同。

Hope this helped :)

希望这有帮助:)

回答by Chris Parker

This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:

在这一点上,这可能比您需要的答案更多。但是,正如其他几个人已经指出的那样,您需要 OR 运算符“||”。有几点没有其他人提到:

1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.

1) If (b.equals("good") || b.equals("it was good")) <-- 如果“b”在这里为空,你会得到一个空指针异常(NPE)。如果您真的在查看硬编码值,就像您在这里一样,那么您可以反转比较。例如

if ("good".equals(b) || "it was good".equals(b))

if ("good".equals(b) || "it was good".equals(b))

The advantage of doing it this way is that the logic is precisely the same, but you'll neverget an NPE, and the logic will work just how you expect.

这样做的好处是逻辑完全相同,但您永远不会得到 NPE,并且逻辑将按照您的预期工作。

2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:

2) Java 使用“短路”测试。通俗地说,这意味着一旦确定结果,Java 就会停止测试条件,即使尚未测试所有条件。例如:

if((b != null) && (b.equals("good") || b.equals("it was good")))

if((b != null) && (b.equals("good") || b.equals("it was good")))

You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.

由于短路性质,您不会在上面的代码中获得 NPE。如果“b”为空,Java 可以放心,无论下一个条件的结果如何,答案始终为假。所以它不会打扰执行这些测试。

Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)

同样,这可能比您在现阶段准备处理的信息多,但在不久的将来某个时候,您测试的 NPE 会咬您。:)

回答by Lew Bloch

There is a simpler way.

有一个更简单的方法。

if (b.contains("good")) {
  ...
}
else if (b.contains("bad")) {
  ...
}