How to write conditional statements and loop structures?

In Java, you can use conditional statements (such as if statements and switch statements) and looping constructs (such as for loops, while loops, and do-while loops) to control the flow of program execution. Here's their basic usage:

Conditional statements:

  1. if statement:

     

    javaCopy code

    if (条件) { // 条件为真时执行的代码块 } else { // 条件为假时执行的代码块 }

  2. if-else if-else statement:

     

    javaCopy code

    if (条件1) { // 条件1为真时执行的代码块 } else if (条件2) { // 条件2为真时执行的代码块 } else { // 所有条件都为假时执行的代码块 }

  3. switch statement:

     

    javaCopy code

    switch (表达式) { case 值1: // 当表达式的值等于值1时执行的代码块 break; case 值2: // 当表达式的值等于值2时执行的代码块 break; // 可以有更多的case语句 default: // 当表达式的值与所有case的值都不匹配时执行的代码块 }

Loop structure:

  1. for loop:

     

    javaCopy code

    for (初始化语句; 循环条件; 更新语句) { // 循环体内的代码块 }

  2. while loop:

     

    javaCopy code

    while (循环条件) { // 循环体内的代码块 // 在循环体内需要更新循环条件,否则可能导致无限循环 }

  3. do-while loop:

     

    javaCopy code

    do { // 循环体内的代码块 // 在循环体内需要更新循环条件,否则可能导致无限循环 } while (循环条件);

These conditional statements and looping constructs enable you to control the flow of program execution based on conditional or looping conditions. Conditional statements allow you to execute different blocks of code based on different conditions, while looping constructs allow you to repeatedly execute a block of code until a certain condition is met. By using these structures flexibly, you can write complex logic and loop control programs according to your needs.

Example:

  1. Use the if statement to check whether a number is positive or negative:

     

    javaCopy code

    int num = 10; if (num > 0) { System.out.println("数是正数"); } else if (num < 0) { System.out.println("数是负数"); } else { System.out.println("数是零"); }

  2. Use a for loop to calculate the sum from 1 to 10:

     

    javaCopy code

    int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } System.out.println("1到10的和为:" + sum);

  3. Use a while loop to print the numbers from 1 to 5:

     

    javaCopy code

    int i = 1; while (i <= 5) { System.out.println(i); i++; }

  4. Use a do-while loop to validate the password entered by the user:

     

    javaCopy code

    Scanner scanner = new Scanner(System.in); String password; do { System.out.println("请输入密码:"); password = scanner.nextLine(); } while (!password.equals("123456")); System.out.println("密码正确,登录成功!");

These conditional statements and loop structures are commonly used control structures in Java, which can control the execution flow of the program according to the conditions and loop conditions.

Guess you like

Origin blog.csdn.net/weixin_44798281/article/details/131170765