简体   繁体   中英

Cannot break out of while loop in java

i am unable to break out of while loop, please check out and recommend me how to do it

public class Admin {
boolean exit=false;
public Admin(){
    while (!exit){
    printInstructions();
    }
}
public void printInstructions(){
    System.out.println("check 1 to print hi");
    System.out.println("check 2 to exit");
    Scanner scanner=new Scanner(System.in);
    int choice=scanner.nextInt();
    scanner.nextLine();
    choose(choice);
}
public void choose(int choice){
    switch(choice){
        case 1:
            System.out.println("hi");
            break;
        case 2:
            exit=true;
            break;
    }
}
}

i expected the code to stop executing but on the contrary it is running a number of times. but the while loop is running over and over. i wonder why?

Add break or return in both switch statements to leave the switch altogether. After that it will return to while statement, evaluate boolean exit and exit the loop when it's false .

 public void choose(int choice){
    switch(choice){
      case 1:
        System.out.println("hi");
        break;
      case 2:
        exit=true;
        break;
    }
  }

It is fine that you are trying to decomposite your code to smaller methods/functions. But it will be better if your functions will be interact with each other. To make it possible your functions must return some value as a result of the execution:

// returns exit flag
public bool choose(int choice){
    switch(choice){
        case 1:
            System.out.println("hi");
            return false;
        case 2:
            return true;
    }
}

// print instructions and return the choose
public int printInstructions(){
    System.out.println("check 1 to print hi");
    System.out.println("check 2 to exit");
    Scanner scanner=new Scanner(System.in);
    int choice=scanner.nextInt();
    scanner.nextLine();
    return choice;
}


public Admin(){
    while (!exit){
      int result = printInstructions();
      exit = choose(result);
    }
}

I write code in the browser so it can still have some small mistakes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM