Switch statement loops through - java

I'm trying to make a simple Menu with the switch statement. However i'm having a problem with the switch:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException{
char selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char)System.in.read();
switch(selection){
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
}
}
while(selection != '3');
}
}
For some reason, when selecting either one or two, the result is that print menu gets printed twice, like this:
Program output:
Choose option:
1. opt1.
2. opt2.
3. opt3.
1
opt1 chosen
Choose option:
1. opt1.
2. opt2.
3. opt3.
Choose option:
1. opt1.
2. opt2.
3. opt3.
The question is, what causes this problem?

When you press a number and <Enter> this is two characters not one. i.e. you are typing
1\n
This is unavoidable, but you can chose to parse the input differently with Scanner which handles this differently, or you can ignore it. (or you can expect the user must type a \n after a number...

As Peter pointed out, the problem arises because of the way you are reading the 'selection' input. You can correct the functionality as follows:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException {
char selection = '0';
while (selection != '3') {
if (selection != '\n') {
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
}
selection = (char) System.in.read();
switch (selection) {
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
default:
break;
}
}
}
}

Peter Lawrey is right
I'm suggest using Scanner class :
public static void printMenu() throws IOException {
Scanner scanner = new Scanner(System.in);
int selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char) scanner.nextInt();
switch(selection){
case 1:
System.out.printf("opt1 chosen\n");
break;
case 2:
System.out.printf("opt2 chosen\n");
break;
case 3:
break;
}
scanner.nextLine();
}
while(selection != '3');
}

Related

How to fix my do while loop in order to have the menu appear again and again until the user presses Letter 'Q'?

Here's my code:
import java.util.Scanner;
// I want to call the menu function in my driver class and in a do while loop .
public class Driver {
public static void main(String[] args) {
do {
Scanner scanner = new Scanner(System.in);
char choice = scanner.next().charAt(0);
} while (choice == 'Q');// How to exit the menue
}
static void createNewEmployee() {
System.out.println("What is the name of employee?");
}
static void process() {
char choice;
switch (choice) {
case 'N':
System.out.println("new employee");
createNewEmployee();
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
default:
System.out.println("Error");
}
}
}
Change while (choice == 'q') into while (choice != 'q'). Think of it like "if the user presses anything apart from 'q', carry on".
I think this will help you!!
public static void main(String[] args) {
char choice;
do {
Scanner scanner = new Scanner(System.in) ;
System.out.print("Press Any Key: N -- New, P -- Paycheck, R -- Raise Wages,-- List Employee, Q -- Quit: ");
choice = scanner.next().charAt(0);
process(choice);
} while(choice !='Q');
}
static void process(char choice) {
switch (choice) {
case 'N':
System.out.println("new employee");
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
case 'Q':
System.out.println("Thanks!!");
break;
default:
System.out.println("Error");
}
}

How do I go back to my previous menu?

I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.

How to make method inside method and catch the name of function above method in java which make the

import java.util.Scanner;
public class allPurpose {
public static void main(String[] args) {
theMain();
}
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void subtraction() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Subtraction\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a - b);
System.out.println("\n \t Subtraction: " + c);
System.out.println("\n!continue");
System.out.println("1. Subtraction");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
subtraction();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void multiplication() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Multiplication\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a * b);
System.out.println("\n \t Multiplication: " + c);
System.out.println("\n!continue");
System.out.println("1. Multiplication");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
multiplication();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void division() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Division\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a / b);
System.out.println("\n \t Division: " + c);
System.out.println("\n!continue");
System.out.println("1. Division");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
division();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void table() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Table\n");
System.out.print("Enter Number to get Table of it \t");
int a = sc.nextInt();
for (int i = 1; i<=10; i++){
int b = a*i;
System.out.println(a + " * " + (i) + " = " +b);
}
System.out.println("\n!continue");
System.out.println("1. Table");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
table();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void squareAndCube() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter one number to check its Square and Cube \t ");
int a = sc.nextInt();
int s = (a * a);
int c = (a * a * a);
System.out.println("\t Square: " + s + "\n \tCube: " + c);
System.out.println("\n!continue");
System.out.println("1. Square and Cube");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
squareAndCube();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void exit() {
System.out.println("\n \tThank you have a nice day ahead! :)");
}
}
I am making calculator in java with many features
We can see that I have added following code on every method
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
just the difference is second line of every method is different, in above example code its
System.out.println("1. Addition");
in above example its addition according to the method name (in Addition method it used so )
in subtraction method it is subtraction
and so on
so can we make one method to keep all of the above code and in that code also we do something which auto catch second line according to method in which we are using
like in division second line of it will System.out.println("1. Division"); which auto catch according to the method
First of all, System.out.println is not the only place where your methods differ, but also (more important) in case 1 of switch construct where each method recursively calls itself. Second, there is a problem with your design, whose solution will also solve the original problem. Notice that from each method you are calling another method, even in the case when user requested going back to Main Menu. Stack gets larger and larger! So let's first rewrite theMain method:
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
int n = 0;
while (n != 7) {
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
}
As you can see, we are in the loop which breaks in case that user wants to leave the program.
Now let's rewrite one of methods:
public static void addition() {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
if (!proceed("Addition"))
break;
}
}
And finally, code of proceed method:
public static bool proceed(String method) {
System.out.println("\n!continue");
System.out.println("1. " + method);
System.out.println("2. Main Menu");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
return true;
case 2:
return false;
default:
System.out.println("Invalid input");
break;
}
}
Notice that exit is now only possible from Main Menu.
Answer to your question - method name can be retrieved through reflection, but I believe that is an overkill for this simple program.
Consider using interfaces to make more generic methods; for example, addition/subtraction/multiplication and division can be modeled as one method as follows:
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator("Addition", (a,b) -> a+b);
break;
case 2:
doCalculator("Subtraction", (a,b) -> a-b);
break;
case 3:
doCalculator("Multiplication", (a,b) -> a*b);
break;
case 4:
doCalculator("Division", (a,b) -> a/b);
break;
The generic calculator which takes two inputs, and outputs one value:
public static void doCalculator(String title, Calculator calc) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected "+title+"\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = calc.calculate(a, b);
System.out.println("\n \t "+title+": " + c);
System.out.println("\n!continue");
System.out.println("1. "+title);
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator(title, calc);
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
sc.close();
}
The key is to use an interface which models the calculation:
interface Calculator {
int calculate(int a, int b);
}
You can create other interfaces which closely model other types of calculations to expand the flexibility of this approach.
You can avoid using reflection if you add a simple interface:
public class allPurpose {
//All current methods here
interface Action{
void doOption();
}
}
Then, just index into the array of your methods.
In theMain() you can do:
public static void theMain() {
//Other code here
//instead of switch statement do:
Action[] initialOptions = new Action[] {
new Action() { public void doOption() { addition(); } },
new Action() { public void doOption() { subtraction(); } },
new Action() { public void doOption() { multiplication(); } },
new Action() { public void doOption() { division(); } },
new Action() { public void doOption() { table(); } },
new Action() { public void doOption() { squareAndCube(); } },
new Action() { public void doOption() { exit(); } },
};
int n = sc.nextInt();
if(n < 1 || > 7)
System.out.println("Invalid input");
else
actions[n-1].doOption();
}
Use a helper method in the other methods, where repeat is the current method:
public static void continueOptions(int i, Action repeat){
Action[] options = new Action[] {
repeat,
new Action() { public void doOption() { theMain(); } },
new Action() { public void doOption() { exit(); } },
};
if(i < 1 || > 3)
System.out.println("Invalid input");
else
options[i-1].doOption();
}
After this, for example addition would look like:
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
continueOptions(int i, new Action() { public void doOption() { addition(); } });
}
You can pass a parameter to a method and use switch case inside that method :
public static void callthismethod(int number){
System.out.println("\n!continue");
switch (number) {
case 1 : System.out.println("1. Addition");break;
case 2 : System.out.println("1. Subtraction");break;
case 3 : System.out.println("1. Multiplication");break;
..............
..............
..............
}
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
switch (n) {
case 1:
if(number == 1){
addition();
}
else if(number == 2){
subtraction();
}
else if(number == 3){
multiplication();
}
...........
...........
...........
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}

java.util.NoSuchElementException: No line found, do I need to handle this exception?

My program compiles, but I am getting run time exceptions, not sure if I need to handle them? methods commented out and for extended class, they just display text. I also don't know if I am using labels correctly? I want my program to loop and handle exceptions for erroneous characters, which it does, but it should only terminate if the user enters "5".
import java.util.*;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Mainmenu3 {
// extends premierLeagueClubs
public static void main(String args[]){
boolean shouldExit = false;
int option = 0;
loop: while (!shouldExit) {
try{
Scanner in = new Scanner(System.in);
menu();
System.out.println("\n");
option = in.nextInt();
} // end try
catch(InputMismatchException e) {
String option2 = Integer.toString(option);
} // end catch
switch (option) {
case 1:
chooseTeam();
break;
case 2:
createProfile();
break;
case 3:
loadSave();
break;
case 4:
credits();
break;
case 5:
break loop;
default:
System.out.println("Invalid choice");
}
} // end switch
} // end main method
public static void chooseTeam(){
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Select Team : ");
System.out.println("1. Arsenal");
System.out.println("2. Aston Villa");
System.out.println("3. Bournemouth");
System.out.println("4. Chelsea");
System.out.println("5. Crystal Palace");
System.out.println("6. Everton");
System.out.println("7. Leicester City");
System.out.println("8. Liverpool");
System.out.println("9. Manchester United");
System.out.println("10. Manchester City");
System.out.println("11. Newcastle United");
System.out.println("12. Norwich City");
System.out.println("13. Southampton");
System.out.println("14. Stoke City");
System.out.println("15. Sunderland");
System.out.println("16. Swansea City");
System.out.println("17. Tottenham Hotspur");
System.out.println("18. Watford");
System.out.println("19. West Brom");
System.out.println("20. West Ham United");
int option = 0;
Scanner in = new Scanner(System.in);
//menu();
System.out.println("\n");
option = in.nextInt();
System.out.println("You entered : " + option);
} // end chooseTeam
public static void createProfile(){
} // end createProfile
public static void loadSave(){
} // end loadSave
public static void credits(){
} // end credits
public static void menu(){
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Created by Darren Estcourt");
System.out.println("\n");
System.out.println("Please choose an option : ");
System.out.println("\n");
System.out.println("1. Choose team");
System.out.println("\n");
System.out.println("2. Create profile");
System.out.println("\n");
System.out.println("3. Load/Save game");
System.out.println("\n");
System.out.println("4. Credits");
System.out.println("\n");
System.out.println("5. Quit");
System.out.println("\n");
String option="0";
Scanner in = new Scanner(System.in);
System.out.println("\n");
option = in.nextLine();
switch (option) {
case "1":
chooseTeam();
break;
case "2":
createProfile();
break;
case "3":
loadSave();
break;
case "4":
credits();
break;
case "5":
System.out.println("Goodbye!");
default:
System.out.println("Please select an option between 1 and 4");
//menu();
} // end switch
} // end menu
} // end class
There are multiple issues with your program:
you define shouldExit but nowhere do you update it according to user input
you scan and process user input both in main() and in menu(). generally, your code isn't structured in a coherent readable manner and there is little reuse.
println() already prints a new line (as opposed to print())
for the love of programming goddess - do not use System.exit() to terminate a Java program
here is an example of a working class with the above guidelines implemented to a pasable degree :
import java.util.*;
public class Mainmenu3
{
static Scanner in;
public static void main(String args[])
{
in = new Scanner(System.in);
boolean shouldExit = false;
while (!shouldExit) {
displayMenu();
shouldExit = processUserInput();
}
}
public static void displayMenu()
{
System.out.println();
System.out.println("Created by Darren Estcourt");
System.out.println("Please choose an option : ");
System.out.println("1. Choose team");
System.out.println("2. Create profile");
System.out.println("3. Load/Save game");
System.out.println("4. Credits");
System.out.println("5. Quit");
}
public static int getUserInput()
{
int option = -1;
try {
option = in.nextInt();
} catch (InputMismatchException e) {
// When a scanner throws an InputMismatchException,
// the scanner will not pass the token that caused the exception,
// so that it may be retrieved or skipped via some other method.
in.next();
} catch (NoSuchElementException e) {
// input is exhausted
option = 5;
} catch (IllegalStateException e) {}
// scanner is closed
option = 5;
}
return option;
}
public static boolean processUserInput()
{
int option = getUserInput();
switch (option) {
case 1:
chooseTeam();
break;
case 2:
createProfile();
break;
case 3:
loadSave();
break;
case 4:
credits();
break;
case 5:
System.out.println("Goodbye!");
return true;
default:
System.out.println("Invalid choice");
}
return false;
}
public static void chooseTeam()
{
System.out.println();
System.out.println("Select Team : ");
System.out.println("1. Arsenal");
System.out.println("2. Aston Villa");
System.out.println("3. Bournemouth");
System.out.println("4. Chelsea");
System.out.println("5. Crystal Palace");
System.out.println("6. Everton");
System.out.println("7. Leicester City");
System.out.println("8. Liverpool");
System.out.println("9. Manchester United");
System.out.println("10. Manchester City");
System.out.println("11. Newcastle United");
System.out.println("12. Norwich City");
System.out.println("13. Southampton");
System.out.println("14. Stoke City");
System.out.println("15. Sunderland");
System.out.println("16. Swansea City");
System.out.println("17. Tottenham Hotspur");
System.out.println("18. Watford");
System.out.println("19. West Brom");
System.out.println("20. West Ham United");
int option = getUserInput();
System.out.println("You entered : " + option);
} // end chooseTeam
public static void createProfile()
{
System.out.println("createProfile");
}
public static void loadSave()
{
System.out.println("loadSave");
}
public static void credits()
{
System.out.println("credits");
}
}

Java How can I break a while loop under a switch statement?

I have a homework to implement a simple testing application, below is my current code:
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");
}
}
What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?
You can label your while loop, and break the labeled loop, which should be like this:
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");
}
}
And the label can be any word you want, for example "loop1".
You need a boolean variable e.g. 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;
Put the while inside a function and when you press 0 instead of break just return. For example :
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");
}
}
}
}
How to terminate inner menu ?
Example Code :
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");
}
}
}
}

Categories