第16天

条件语句:java中的条件控制

Java使用条件语句(例如if-else语句)来控制程序流程,根据条件的真假执行不同的代码块。if-else语句包含一个初始条件,以及针对条件为真和为假时的不同代码块。程序根据条件的评估结果(true或false)选择执行相应的代码块。

条件语句类型:

  1. if语句:如果条件为真,则执行语句块;否则不执行任何操作。

  2. if-else语句:如果条件为真,则执行if块;否则执行else块。

  3. if-else-if语句:允许检查多个条件,依次执行满足条件的代码块,直到找到一个为真的条件或执行完所有条件。

  4. switch语句:根据表达式的值选择执行不同的代码块。

if语句示例:

package day1if;

public class Main {
    public static void main(String[] args) {
        int bat = 500;
        if (bat >= 500) {
            System.out.println("go to play");
        }
        System.out.println("don't play"); // 这行代码无论条件是否成立都会执行
    }
}

输出:

go to play
don't play

if-else语句示例:

package day1if;

public class Main1 {
    public static 

void main(String[] args) { int bat = 500; if (bat > 600) { System.out.println("go to play"); } else { System.out.println("don't play"); } } }

输出:

don't play

if-else-if语句:

(此处应补充if-else-if语句的示例代码和解释) if-else-if语句允许测试多个条件,代码结构如下:

if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else if (condition3) {
    // Code to execute if condition3 is true
} else {
    // Code to execute if none of the above conditions are true
}

通过以上示例和解释,可以清晰地理解Java中不同类型的条件语句及其使用方法。 请注意,示例代码中存在一些小问题,例如第一个例子中"don't play"的输出不受if语句控制,第二个例子中变量名大小写不一致(string应该为String)。 修改后的代码更符合规范。