Understanding Java while loops - java

Hi am new to java programming and I am trying to understand while loops. I haven't used it in the code below but I have an assignment that requires me to. What I want the program to do is simply re prompt the user to enter a menu option 1 to 5 when the code in the switch statement executes based on the user input. I am unsure where to put the while loop in the code and also what to write inside of it. Can someonme please help me with the program I am to create? It also requires me to use a switch statement to evalute the user input. All comments would be appreciated!
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
get_method();
}
public static void get_method() {
int num;
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}

If I understand your question correctly you will want to put the while loop around the call for the action. In your case you have not specified if one of the options exits or on what condition the program should exit. In that case I have to assume that it loops indefinently. The code could be as below.
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
while(true) {
get_method();
}
}
public static void get_method() {
int num;
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}
The addition would be the
while(true) {
get_method();
}
You could also restructure it to add a continue option. Or to exit on one of the options say option 5 is the exit option than the program could be written as follows:
import java.util.Scanner;
public class Student_Grade {
public static void main(String[] args) {
get_method();
}
public static void get_method() {
int num;
while(num != 5) {
Scanner menu = new Scanner(System.in);
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
switch (num = menu.nextInt()) {
case 1:
System.out.println("You entered menu option 1");
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 3");
break;
default:
System.out.println("You entered an invalid option");
break;
}
}
}
}
There are a number of different ways to handle loops but this should get you started.

do_While loop is best for menu driven application as per your code structure
do{
System.out.println("Please Enter menu 1 and 5 and 0 to exit");
System.out.println(" menu option 1");
System.out.println(" menu option 2");
System.out.println(" menu option 3");
System.out.println("menu option 4);
System.out.println(" menu option 5");
int num= menu.nextInt();
switch (num) {
case 1:
System.out.println("You entered menu option 1");
//you can write while loop here or
// call new method which deals with while loop
break;
case 2:
System.out.println("you entered menu option 2");
break;
case 3:
System.out.println("you entered menu option 3");
break;
case 4:
System.out.println("you entered menu option 4");
break;
case 5:
System.out.println("you entered menu option 5");
break;
case 0:
System.out.println("you entered menu option ");
exit(0);
break;
default:
System.out.println("You entered an invalid option");
break;
}
System.out.println("do you want to continue? Y/N");
}while(choice!='Y');

Related

how to implement returning to previous menu from a menu implemented through switch?

I am writing a program where the user inputs a choice in the main menu and it takes them to another sub-menu. I want one of the options to be "return to previous menu" i.e. the menu first shown to the user. I can not really figure out how to do this in the way I have set up my code. Here is my code for the PrintMenu method:
public static void PrintMenu(){
Scanner input = new Scanner (System.in);
int option = 0;
while(option != 3){
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Stack");
System.out.println("2 Queue");
System.out.println("3 Quit");
option = input.nextInt();
switch(option){
case 1:
{
//add code for stack
System.out.println("You are currently using a stack. \n");
System.out.println("Enter the maximum size you want for your stack: ");
maxSize = input.nextInt();
int option_stack = 0;
while(option_stack != 5){
System.out.println("Menu Please enter an option given
bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Add to Stack");
System.out.println("2 Remove from Stack");
System.out.println("3 Clear Stack");
System.out.println("4 Return to previous menu");
System.out.println("5 Quit");
option_stack = input.nextInt();
switch(option_stack){
case 1:
{
//add code for Add to Stack
break;
}
case 2:
{
//add code for Remove from Stack
break;
}
case 3:
{
//add code for Clear Stack
break;
}
case 4:
{
//add code for Return to previous menu
break;
}
case 5:
System.exit(0);
break;
//Error message if user inputs anything other
than 1-5
default:
System.out.println(option + " is not a
correct choice.\n"
+ "please enter
another option. \n");
break;
}
}
break;
}
case 2:
{
//add sub-menu and corresponding code for queue in the same
//way as stack
}
}
}
What can I put in case 4 that would take the user to the main menu?
A good point to start is this skeleton below.
Let me explain some points:
Don't use static methods if you have no good reason to do!
Please have a look to this discussion
Keep your switch statements as short as possible and avoid nesting!
The longer the switch statement the more difficult is it to keep track of it.
The deeper the nesting the higher the complexity.
A good way to avoid both is to put the code of each case in a seperate method or to encapsulate in it's own class.
Don't use curly brackets for case blocks.
They are avoidable noise (especially if you follow bullet point 2).
In the Main class create a instance of it self to get out of the 'static trap'.
The startable Main class containing the main menu:
package joker5309;
import java.util.Scanner;
public class Menu {
public void mainMenu() {
Scanner input = new Scanner(System.in);
int option = 0;
while (option != 3) {
System.out.println("do stuff for main menu ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Stack");
System.out.println("2 Queue");
System.out.println("3 Something else");
System.out.println("4 Quit");
option = input.nextInt();
switch (option) {
case 1:
StackHandler stackHandler = new StackHandler();
stackHandler.doIt(input);
break;
case 2:
// add sub-menu and corresponding code for queue in the same
// way as stack
QueueHandler queueHandler = new QueueHandler();
queueHandler.doIt(input);
break;
case 3:
// add any other submenue ...
SomethingElseHandler seHandler = new SomethingElseHandler();
seHandler.doIt(input);
break;
case 4:
System.exit(0);
} // hctiws
} // elihw
} // mainMenu()
public static void main(String[] args) {
// create an instance of Menu class to leave the 'static trap'
Menu mySelf = new Menu();
mySelf.mainMenu();
} // main()
} // sslac
A seperate handler class for each meun item:
package joker5309;
import java.util.Scanner;
public class StackHandler implements Handler {
#Override
public void doIt(Scanner input) {
// add code for stack
System.out.println("You are currently using a stack. \n");
System.out.println("Enter the maximum size you want for your stack: ");
input.nextInt();
int optionStack = 0;
while (true) {
System.out.println("do stuff for stack ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Add to Stack");
System.out.println("2 Remove from Stack");
System.out.println("3 Clear Stack");
System.out.println("4 Return to previous menu");
System.out.println("5 Quit");
optionStack = input.nextInt();
switch (optionStack) {
case 1:
// add code for Add to Stack
stackAdd();
break;
case 2:
// add code for Remove from Stack
stackRemove();
break;
case 3:
// add code for Clear Stack
stackClear();
break;
case 4:
// add code for Return to previous menu
return;
case 5:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionStack + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // stackParameter()
private void stackAdd() {
System.out.println("stackAdd()");
}
private void stackRemove() {
System.out.println("stackRemove()");
}
private void stackClear() {
System.out.println("stackClear()");
}
}
package joker5309;
import java.util.Scanner;
public class QueueHandler implements Handler {
#Override
public void doIt(Scanner input) {
int optionQueue = 0;
while (true) {
System.out.println("do stuff for queue ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 ...");
System.out.println("2 Return to previous menu");
System.out.println("3 Quit");
optionQueue = input.nextInt();
switch (optionQueue) {
case 1:
// add code for ...
break;
case 2:
// add code for Return to previous menu
return;
case 3:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionQueue + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // queueParameter()
}
package joker5309;
import java.util.Scanner;
public class SomethingElseHandler implements Handler {
#Override
public void doIt(Scanner input) {
int optionStack = 0;
while (true) {
System.out.println("do stuff for something else ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 ...");
System.out.println("2 Return to previous menu");
System.out.println("3 Quit");
optionStack = input.nextInt();
switch (optionStack) {
case 1:
// add code for ...
break;
case 2:
// add code for Return to previous menu
return;
case 3:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionStack + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // queueParameter()
}

Can we add a back feature to a do while menu selector in java?

So I was working on a project for university, and I decided to use the classic do-while loop with a switch case in it to make a selector menu, but I want it instead of it asking the user for another case immediately after performing one, I want kind of like a back menu button, I searched the web but couldn't find a similar question to mine.
I included my code down below, so for example if I chose case 1, it will print "case 1" and then reprint the menu, but I want it to hold until the user enter an input then it will loop to the menu again.
Any help would be appreciated and thank you in advance.
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
break;
case 2:
System.out.println("case 2");
break;
case 3:
System.out.println("case 3");
break;
case 4:
System.out.println("case 4");
break;
case 5:
System.out.println("Exiting in process...");
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
break;
}
} while (operator != 5);
input.close();
}
}
Here is the answer to your question:
import java.util.Scanner;
// Import java.util for TimeUnit
import java.util.concurrent.TimeUnit;
public class Main {
// Create the wait function
public static void wait(int ms){
try {
Thread.sleep(ms);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
/** Add wait(3000); to every line! This will allow
the code to hold 3 seconds before returning back to the menu**/
wait(3000);
break;
case 2:
System.out.println("case 2");
wait(3000);
break;
case 3:
System.out.println("case 3");
wait(3000);
break;
case 4:
System.out.println("case 4");
wait(3000);
break;
case 5:
System.out.println("Exiting in process...");
wait(1000);
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
wait(3000);
break;
}
} while (operator != 5);
input.close();
}
}
I used a TimeUnit util to create a wait function. This wait function works as:
wait(int ms)

Adding a loop to a displayed menu so that it is displayed repeatedly until the last option is selected and stop the loop

I have created a display menu and want to add a loop to continuously display the menu until the last option is selected. Not sure if I am doing it right.
Let me know if there is anywhere I can add on thanks!
import java.util.Scanner;
public class loopTest
{
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit");
System.out.println("Please enter your choice: ");
}
public void start()
{
Scanner console = new Scanner(System.in);
String s = "";
while(s < size())
{
displayMenu();
console.nextLine();
switch (s.charAt(0))
{
case 'A': System.out.println("A. Option #A"); break;
case 'B': System.out.println("B. Option #B"); break;
case 'C': System.out.println("C. Option #C"); break;
case 'D': System.out.println("D. Option #D"); break;
case 'X': System.out.println("X. Exit"); break;
default: System.out.println("Error, please enter a valid
character");
}
}
s++;
}
}
consider using a boolean variable
boolean wantToExit = false;
while (!wantToExit ) {
.... // switch
case 'X':
wantToExit = true;
System.out.println("X. Exit");
break;
}
note
s is a string, there is no < comparator nor s++ incrementor
Also, you are not assign a value to s from the Console input

How to make program catch error in exception handling-Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi guys so my program doesn't really catch any errors i.e. when I input a letter instead of a valid number it does catch the error but it doesn't return back to the menu , it just displays the statement. And when I use a number outside of the switch statement i.e. 5 it just loops back to the menu without displaying error. My code is below:
public void runMenu() {
Scanner Option = new Scanner (System.in);
int x = 1;
int Choice = 0;
do{
try{
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice= Option.nextInt();
switch (Choice) //used switch statement instead of If else because more effective
{
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
throw new Exception();
// x=2; //if code doesn't run successfully then x !=2 leading to exception
}
}
The case 4 is not closed with a break therefore you never instantiate your exception !
You should have this at the end of your switch :
default:
throw new Exception();
break;
Also, you need to remove the return from catch section.
catch (Exception e){
System.err.println("Enter Correct Input");
return ;
}
for when you've entered a number other than 1-4 you should have a default option,
to re-run the questions after you've displayed an error message call runMenu()
for example,
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
println "Choose 1-4";
runMenu()
Hope this helps.
This really isn't a situation where an exception is normally thrown. If you want the program to just loop back to the menu if the user enters an invalid option, you should only have to add a default case to your while loop. You don't even need your x integer for that. You can try throwing a new Exception in the default case if you want.
import javax.swing.*;
import java.util.Arrays;
import java.util.Scanner;
public class runMenu {
public void runMenu() {
Scanner Option = new Scanner (System.in);
int Choice = 0;
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice= Option.nextInt();
switch (Choice) //used switch statement instead of If else because more effective
{
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
// x=2; //if code doesn't run successfully then x !=2 leading to exception
throw new Exception();
break;
default:
System.out.println("Invalid option. Please try
again.");
throw new Exception();
runMenu();
}
}
}
}

How to use loops in Java

I need help on how to use for-loops in Java
This is an assignment for class, so I'd rather just be pointed in the right direction instead of given an answer.
"List of valid seven dwarfs: Sleepy, Bashful, Doc, Sneezy, Happy, Grumpy, Dopey
Pool of random characters, non-valid Dwarfs: Lion-O, Cheetara, Panthro, Tigra, Snarf, Donald Duck, Mickey Mouse, Minnie Mouse, Goofy, Heathcliff, Huey, Dewey, Louie, Scrooge McDuck,
Declare these variables:
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
Print a list of three choices to the console. Ask the user to pick the correct dwarf of the three choices.
The list of three choices will include two names from the random characters list and one name from the seven dwarfs.
You will create a switch statement to handle the choice selection
When the wrong case is selected then decrement the int variable called counter and print to the console “wrong selection”
When the correct case is selected then change the corresponding boolean variable to true (ie.. firstSelection, secondSelection, etc) and print to the console “Hi Ho, you picked the correct one”
The default case will print a statement to the console “invalid selection”
Create a loop that will perform this seven times until you covered all seven dwarfs.
Use a for loop
Recreate the loop again using a do-while loop
Recreate the loop again using a while loop
At the end, create an if-else statement. This statement will have short circuit &&’s that will test all of the Boolean variables. If true, print a statement to the console “You earned a gold star!”. Else, print a statement to the console “You did not get all correct”. "
I completed the previous assignment, which was just this specification without the loops, with no problem. However I really don't understand how the professor wants us to integrate the loops into the problem. The only thing I can think of is that he wants up to create a loop seven times that somehow asks about a different dwarf each of the seven times. Is that even possible? Can you change the content of the loops as you are running through it? I feel like I am just not even thinking about this correctly.
Here is my code from the previous assignment, sans loops:
import java.util.Scanner;
public class SevenDwarfs {
public static void main(String[] args) {
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Sleepy");
System.out.println("2 Lion-O");
System.out.println("3 Cheetara");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hi Ho, you picked the correct one");
firstSelection = true;
break;
case 2:
System.out.println("Wrong selection");
--counter;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Panthro");
System.out.println("2 Bashful");
System.out.println("3 Tigra");
Scanner input2 = new Scanner(System.in);
int choice2 = input2.nextInt();
switch (choice2) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
secondSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Snaf");
System.out.println("2 Doc");
System.out.println("3 Donald Duck");
Scanner input3 = new Scanner(System.in);
int choice3 = input3.nextInt();
switch (choice3) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
thirdSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Mickie Mouse");
System.out.println("2 Sneezy");
System.out.println("3 Minie Mouse");
Scanner input4 = new Scanner(System.in);
int choice4 = input4.nextInt();
switch (choice4) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fourthSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Heathcliff");
System.out.println("2 Happy");
System.out.println("3 Goofy");
Scanner input5 = new Scanner(System.in);
int choice5 = input5.nextInt();
switch (choice5) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fiveSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Huey");
System.out.println("2 Grumpy");
System.out.println("3 Dewey");
Scanner input6 = new Scanner(System.in);
int choice6 = input6.nextInt();
switch (choice6) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sixSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Scrooge McDuck");
System.out.println("2 Dopey");
System.out.println("3 Louie");
Scanner input7 = new Scanner(System.in);
int choice7 = input7.nextInt();
switch (choice7) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sevenSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
if (firstSelection == true && secondSelection == true
&& thirdSelection == true && fourthSelection == true
&& fiveSelection == true && sixSelection == true
&& sevenSelection == true) {
System.out.println("You earned a gold star!");
} else {
System.out.println("\nYou did not get all correct.");
}
}
}
The fact that you realized you might be thinking about the concept incorrectly and asked for help is a good thing.
Read the following to get familiar with loops in Java.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To answer your question, yes, you can change the content of a loop as you run it. That's what variables are for. You can modify their values as your program runs. Look at this sample. The variable i increments with every iteration of the loop. The variable outsideLoop also changes inside the loop. Play with this and you'll start to understand.
class ForDemo
{
public static void main(String[] args)
{
int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
outsideLoop += i;
System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);
}
}
You've got a good starting point for the process of printing the selection, getting user input, and validating user input. Repeat that chunk (in a loop) 7 times.

Categories

Resources