Discuss / Java / 一次性跳出多重循环的方法

一次性跳出多重循环的方法

Topic source

YANGZY1202

#1 Created at ... [Delete] [Delete and Lock User]

当我们需要跳出或结束多重循环时,除了在每一个循环体后面加一个break(continue)外,还可以通过label(标号)跳出多重循环(有点类似与goto语句),如下例:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int amount = in.nextInt();
		//使用label(标号)跳出多重循环
		OUT:
		for (int one = 0; one <= amount; ++one) {
			for (int five = 0; five <= amount / 5; ++five) {
				for (int ten = 0; ten <= amount / 10; ++ten) {
					for (int twenty = 0; twenty <= amount / 20; ++twenty) {
						if (one + five * 5 + ten * 10 + twenty * 20 == amount) {
							System.out.println(one + "张1元," + five + "张5元," + ten + "张10元," + twenty + "张20元。");
							break OUT;  //此break可以跳出整个多重循环
						}
					}
				}
			}
		}

	}

}

学习了,赞

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

用到label的时候,说明你的程序太复杂了,想想怎么简化吧

我们老师叫做 flag

里耳LeeEar

#5 Created at ... [Delete] [Delete and Lock User]

和C/C++中的goto语句效果相似,这种任意的跳转可能会违背局部性原则,是一种导致程序运行低效率的做法。

跟C里面的goto差不多,作为知识点了解一下就行了。尽量不要用!尽量不要用!尽量不要用!


  • 1

Reply