If-Else Statement in Java – 在Java中的If-Else语句

最后修改: 2019年 1月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll learn how to use the if-else statement in Java.

在本教程中,我们将学习如何在Java中使用if-else语句。

The if-else statement is the most basic of all control structures, and it’s likely also the most common decision-making statement in programming.

if-else语句是所有控制结构中最基本的,它也可能是编程中最常见的决策语句

It allows us to execute a certain code section only if a specific condition is met.

它允许我们只在满足特定条件时执行某个代码部分

2. Syntax of If-Else

2.If-Else的语法

The if statement always needs a boolean expression as its parameter.

if语句总是需要一个boolean表达式作为其参数

if (condition) {
    // Executes when condition is true.
} else {
    // Executes when condition is false.
}

It can be followed by an optional else statement, whose contents will be executed if the boolean expression is false.

它后面可以有一个可选的else语句,如果布尔表达式是false.,其内容将被执行。

3. Example of If

3.If的例子

So, let’s start with something very basic.

因此,让我们从非常基本的东西开始。

Let’s say that we only want something to happen if our count variable is larger than one:

假设我们只想在我们的count变量大于1的时候发生一些事情。

if (count > 1) {
    System.out.println("Count is higher than 1");
}

The message Count is higher than 1 will only be printed out if the condition passes.

只有当条件通过时,才会打印出Count is higher than 1的信息。

Also, note that we technically can remove the braces in this case since there is only one line in the block. But, we should always use braces to improve readability; even when it’s only a one-liner.

另外,请注意,在这种情况下,我们在技术上可以去掉大括号,因为该块中只有一行。但是,我们应该始终使用大括号来提高可读性;即使只是一个单行字。

We can, of course, add more instructions to the block if we like:

当然,如果我们愿意,我们可以在这个区块中加入更多的指令。

if (count > 1) {
    System.out.println("Count is higher than 1");
    System.out.println("Count is equal to: " + count);
}

4. Example of If-Else

4.If-Else的例子

Next, we can choose between two courses of action using if and else together:

接下来,我们可以用ifelse一起在两个行动方案中进行选择。

if (count > 2) {
    System.out.println("Count is higher than 2");
} else {
    System.out.println("Count is lower or equal than 2");
}

Please note that else can’t be by itself. It has to be joined with an if.

请注意,else不能单独存在。它必须与if连接。

5. Example of If-Else If-Else

5.If-Else If-Else的例子

And finally, let’s end with a combined if/else/else if syntax example.

最后,让我们以一个组合的if/else/else if语法例子来结束。

We can use this to choose between three or more options:

我们可以用它来在三个或更多的选项中进行选择

if (count > 2) {
    System.out.println("Count is higher than 2");
} else if (count <= 0) {
    System.out.println("Count is less or equal than zero");
} else {
    System.out.println("Count is either equal to one, or two");
}

6. Conclusion

6.结论

In this quick article, we learned what if-else statement is and how to use it to manage flow control in our Java programs.

在这篇文章中,我们了解了什么是if-else语句,以及如何使用它来管理我们Java程序中的流程控制。

All code presented in this article is available over on GitHub.

本文介绍的所有代码都可以在GitHub上获得