【Java基础——10 ,break、continue、goto 和 return 】

在 Java 编程中,breakcontinuegotoreturn 是控制流程的关键字。它们用于控制程序的执行流程。

1. break

break 用于终止循环或 switch 语句,并跳出当前循环或 switch 语句的执行。

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break; // Terminates the loop when i is 5
            }
            System.out.println("i: " + i);
        }
    }
}

2. continue

continue 用于跳过当前循环中的剩余语句,并立即开始下一次循环迭代。

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                continue; // Skips the rest of the loop body when i is 5
            }
            System.out.println("i: " + i);
        }
    }
}

3. goto

在 Java 中,没有直接的 goto 关键字,因为它容易导致代码的可读性和可维护性变差。但是,Java 支持通过标签breakcontinue 结合使用来实现类似 goto 的行为。

public class GotoExample {
    public static void main(String[] args) {
        outerLoop: // Label for the outer loop
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (i == 1 && j == 1) {
                    break outerLoop; // Exits both loops when i is 1 and j is 1
                }
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}

4. return

return 用于从方法中返回值或终止方法的执行。

public class ReturnExample {
    public static void main(String[] args) {
        int result = sum(5, 10);
        System.out.println("Sum: " + result);
    }

    public static int sum(int a, int b) {
        return a + b; // Returns the sum of a and b
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值