java 中断语句_Java如何在switch语句下中断while循环?

如何终止内部菜单?

示例代码:

import java.util.Scanner;

public class Example {

public static void main(String[] args) {

Scanner input = new Scanner(System.in); //used to get input

int option1, option2 = 0;

boolean loop_terminate = true; //flag used to terminate inner while loop

//Main Menu

while (true) {

//Main Menu options

System.out.println("1.Option 1");

System.out.println("2.Option 2");

System.out.println("3.Option 3");

System.out.println("4.Option 4");

System.out.println("5.Exit main menu");

System.out.print("Please enter your choice : ");

option1 = input.nextInt();

switch (option1) {

case 1:

//do something here

break;

case 2:

//do something here

break;

case 3:

while (loop_terminate) {

//Inner menu options

System.out.println("1.Inner Menu option 1");

System.out.println("2.Inner Menu option 2");

System.out.println("3.Inner Menu option 3");

System.out.println("4.Return to Main Menu");

System.out.print("Please enter your choice : ");

option2 = input.nextInt();

switch (option2) {

case 1:

break;

case 2:

break;

case 3:

break;

case 4:

loop_terminate = false; //this will terminate inner menu

break;

default:

System.out.println("Invalid option");

break;

}

}

break; //never forget to add this break statement

case 4:

break;

case 5:

return; //terminate outer menu

default:

System.out.println("Invalid option");

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值