Java 简明教程

Java - Decision Making

决策结构具有一条或多条要由程序评估或测试的条件,以及在确定条件为真时要执行的语句,并且在确定条件为假时可以选择执行其他语句。

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

以下是大多数编程语言中常见的典型决策结构的一般形式 −

Following is the general form of a typical decision making structure found in most of the programming languages −

decision making

Java 编程语言提供了以下类型的决策制定语句。单击以下链接以查看它们的详细信息。

Java programming language provides following types of decision making statements. Click the following links to check their detail.

Sr.No.

Statement & Description

1

if statementAn if statement consists of a boolean expression followed by one or more statements.

2

if…​else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.

3

nested if statementYou can use one if or else if statement inside another if or else if statement(s).

4

switch statementA switch statement allows a variable to be tested for equality against a list of values.

The ? : Operator

我们已经在上个章节中介绍了 conditional operator ? :,它可以替换 if…​else 语句。它的通用格式如下 −

We have covered conditional operator ? : in the previous chapter which can be used to replace if…​else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

其中 Exp1、Exp2 和 Exp3 是表达式。请注意冒号的用处和位置。

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

要确定整个表达式的值,最初会求出 exp1 的值。

To determine the value of the whole expression, initially exp1 is evaluated.

  1. If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression.

  2. If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

Example

在这个示例中,我们创建了两个变量 a 和 b,并且使用 ternary operator 决定了 b 的值并打印出来了。

In this example, we’re creating two variables a and b and using ternary operator we’ve decided the values of b and printed it.

public class Test {

   public static void main(String args[]) {
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}

Output

Value of b is : 30
Value of b is : 20

What is Next?

在下一章节中,我们将讨论数字类(在 java.lang 包中)及其在 Java 语言中的子类。

In the next chapter, we will discuss about Number class (in the java.lang package) and its subclasses in Java Language.

我们将研究一些这种情况,在这些情况下,您将使用这些类的实例化,而不是原始数据类型,以及在使用数字时您需要了解的格式化、数学函数等类。

We will be looking into some of the situations where you will use instantiations of these classes rather than the primitive data types, as well as classes such as formatting, mathematical functions that you need to know about when working with Numbers.