java for循环使用标签以及switch

本文通过一个Java示例程序介绍了如何使用带标签的循环进行流程控制,并演示了switch语句的正确使用方法,包括如何针对不同条件执行特定代码块、如何避免常见错误等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class LabeledLoop {

	public static void main(String[] args) {
		int i = 0;
		outer: // Can't have statements here
		for(; true ;) {
			inner: // Can't have statements here
			for(; i < 10; i++) {
				prt("i = " + i);
				if(i == 2) {
					prt("continue");
					continue;
				}
				if(i == 3) {
					prt("break");
					i++; // Otherwise i never gets incremented.
					break;
				}
				if(i == 7) {
					prt("continue outer");
					i++; // Otherwise i never gets incremented.
					continue outer;
				}
				if(i == 8) {
					prt("break outer");
					break outer;
				}
				for(int k = 0; k < 5; k++) {
					if(k == 3) {
						prt("continue inner");
						continue inner;
					}
				}
			}
		}
		// Can't break or continue to labels here
	}
	static void prt(String s) {
		System.out.println(s);
	}
}

 

    * switch要求使用一个选择因子,并且必须是int 或char 那样的整数值。假若将一个字串或者浮点数作为

      选择因子使用,那么它们在switch 语句里是不会工作的。对于非整数类型,则必须使用一系列if 语句。
   * 每个case 均以一个break 结尾。这样可使执行流程跳转至switch 主体的末尾。
   * 若省略break,会继续执行后面的case 语句的代码,直到遇到一个break 为止。

 

输出为:

i = 0
continue inner
i = 1
continue inner
i = 2
continue
i = 3
break
i = 4
continue inner
i = 5
continue inner
i = 6
continue inner
i = 7
continue outer
i = 8
break outer

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值