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可以跳出整个多重循环
						}
					}
				}
			}
		}

	}

}


  • 1

Reply