Control Structures in Java – Java中的控制结构

最后修改: 2019年 1月 5日

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

1. Overview

1.概述

In the most basic sense, a program is a list of instructions. Control structures are programming blocks that can change the path we take through those instructions.

在最基本的意义上,一个程序是一个指令列表。控制结构是可以改变我们通过这些指令的路径的编程块。

In this tutorial, we’ll explore control structures in Java.

在本教程中,我们将探讨Java中的控制结构。

There are three kinds of control structures:

有三种控制结构:

  • Conditional Branches, which we use for choosing between two or more paths. There are three types in Java: if/else/else if, ternary operator and switch.
  • Loops that are used to iterate through multiple values/objects and repeatedly run specific code blocks. The basic loop types in Java are for, while and do while.
  • Branching Statements, which are used to alter the flow of control in loops. There are two types in Java: break and continue.

2. If/Else/Else If

2.If/Else/Else If

The if/else statement is the most basic of control structures, but can also be considered the very basis of decision making in programming.

if/else语句是最基本的控制结构,但也可以认为是编程中决策的基础。

While if can be used by itself, the most common use-scenario is choosing between two paths with if/else:

虽然if可以单独使用,但最常见的使用场景是用if/else在两条路径之间进行选择。

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

Theoretically, we can infinitely chain or nest if/else blocks but this will hurt code readability, and that’s why it’s not advised.

理论上,我们可以无限地连锁或嵌套if/else块,但这将损害代码的可读性,这就是为什么不建议这样做。

We’ll explore alternative statements in the rest of this article.

我们将在本文的其余部分探讨替代性声明。

3. Ternary Operator

3.三元运算符

We can use a ternary operator as a shorthand expression that works like an if/else statement.

我们可以使用三元运算符作为一个速记表达式,其工作方式类似于if/else语句。

Let’s see our if/else example again:

让我们再看看我们的if/else例子。

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

We can refactor this with a ternary as follows:

我们可以用一个三元组来重构这个问题,如下所示。

System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");

While ternary can be a great way to make our code more readable, it isn’t always a good substitute for if/else.

虽然三元组可以使我们的代码更有可读性,但它并不总是if/else.的良好替代。

4. Switch

4.开关

If we have multiple cases to choose from, we can use a switch statement.

如果我们有多种情况可供选择,我们可以使用switch 语句。

Let’s again see a simple example:

让我们再看一个简单的例子。

int count = 3;
switch (count) {
case 0:
    System.out.println("Count is equal to 0");
    break;
case 1:
    System.out.println("Count is equal to 1");
    break;
default:
    System.out.println("Count is either negative, or higher than 1");
    break;
}

Three or more if/else statements can be hard to read. As one of the possible workarounds, we can use switch, as seen above.

三个或更多的if/else 语句会让人难以阅读。作为可能的变通方法之一,我们可以使用switch,如上所示。

And also keep in mind that switch has scope and input limitations that we need to remember before using it.

还要记住,switch有范围和输入限制,我们在使用它之前需要记住。

5. Loops

5.循环

We use loops when we need to repeat the same code multiple times in succession.

当我们需要连续多次重复相同的代码时,我们使用循环

Let’s see a quick example of comparable for and while type of loops:

让我们看看一个可比较的forwhile型循环的快速例子。

for (int i = 1; i <= 50; i++) {
    methodToRepeat();
}

int whileCounter = 1;
while (whileCounter <= 50) {
    methodToRepeat();
    whileCounter++;
}

Both code blocks above will call methodToRepeat 50 times.

上面的两个代码块将调用methodToRepeat50次。

6. Break

6.休息

We need to use break to exit early from a loop.

我们需要使用break来提前退出一个循环。

Let’s see a quick example:

让我们看一个快速的例子。

List<String> names = getNameList();
String name = "John Doe";
int index = 0;
for ( ; index < names.length; index++) {
    if (names[index].equals(name)) {
        break;
    }
}

Here, we are looking for a name in a list of names, and we want to stop looking once we’ve found it.

在这里,我们要在一个名字的列表中寻找一个名字,一旦找到它,我们就想停止寻找。

A loop would normally go to completion, but we’ve used break here to short-circuit that and exit early.

循环通常会进行到结束,但我们在这里使用了break来缩短这个过程并提前退出。

7. Continue

7.继续

Simply put, continue means to skip the rest of the loop we’re in:

简单地说,continue 意味着跳过我们所处的其他循环:

List<String> names = getNameList();
String name = "John Doe";
String list = "";
for (int i = 0; i < names.length; i++) { 
    if (names[i].equals(name)) {
        continue;
    }
    list += names[i];
}

Here, we skip appending the duplicate names into the list.

在这里,我们跳过将重复的名称追加到列表中。

As we’ve seen here, break and continue can be handy when iterating, though they can often be rewritten with return statements or other logic.

正如我们在这里看到的,breakcontinue在迭代时可以很方便,尽管它们通常可以用return语句或其他逻辑重写。

8. Conclusion

8.结语

In this quick article, we learned what control structures are and how to use them to manage flow control in our Java programs.

在这篇快速文章中,我们了解了什么是控制结构,以及如何使用它们来管理我们的Java程序中的流控制。

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

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