Подтвердить что ты не робот

Java Как я могу разбить цикл while в инструкции switch?

У меня есть домашняя работа по внедрению простого тестового приложения, ниже мой текущий код:

import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              break; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
      System.out.println("Test is done");
    }
}

Теперь я хочу сказать, что при нажатии 0 это означает, что пользователь хочет выйти из теста, затем я разбиваю while loop и печатаю Test is done, но он не работает так, Я знаю, причина может быть в том, что "break" разбивает switch, как я могу позволить ему сломать while loop вместо этого?

4b9b3361

Ответ 1

Вы можете label ваш цикл while и break labeled loop, который должен быть следующим:

loop: while(sc.hasNextInt()){
    typing = sc.nextInt();
    switch(typing){
        case 0:
          break loop; 
        case 1:
          System.out.println("You choosed 1");
          break;
        case 2:
          System.out.println("You choosed 2");
          break;
        default:
          System.out.println("No such choice");
    }
}

И label может быть любым желаемым словом, например "loop1".

Ответ 2

Вам нужна логическая переменная, например. shouldBreak.

    boolean shouldBreak = false;
    switch(typing){
        case 0:
          shouldBreak = true;
          break; //Here I want to break the while loop
        case 1:
          System.out.println("You choosed 1");
          break;
        case 2:
          System.out.println("You choosed 2");
          break;
        default:
          System.out.println("No such choice");
    }
    if (shouldBreak) break;

Ответ 3

Поместите время внутри функции и когда вы нажимаете 0 вместо разрыва только return. Например:

    import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    func(sc);
      System.out.println("Test is done");
    }
}

public static void func(Scanner sc) {


    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              return; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
}

}

Ответ 4

Как завершить внутреннее меню?

Пример кода:

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");
            }
        }

    } 
}