Displaying an iterative menu in JAVA - java

I have written the following code in the main function of my program to generate a menu driven program. There are basically six options available on the Menu and the menu() not only displays the menu but also returns the user's choice. If you require the code for that, I'll post it.
public static void main(String args[])throws IOException
{ BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object=new attendance_and_student_management();
int flag=1;
while(flag==1)
{ int var=object.menu();
if(var==1)
{ System.out.println("\f");
object.add_student();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());
}
else if(var==2)
{ System.out.println("\f");
object.search_student();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());
}
else if(var==3)
{ System.out.println("\f");
object.change_student_information();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==4)
{ System.out.println("\f");
object.take_attendance();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==5)
{ System.out.println("\f");
object.attendance_summary();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==6)
{
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag=Integer.parseInt(bw.readLine());;
}
else if(var==7)
{ System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
}
else
{ System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int chhh=Integer.parseInt(bw.readLine());
if(chhh==1)
{ flag=1;
}
else
{ flag=0;
}
}
}
}
Now I am facing only one issue with this code, it goes to a particular method and remains stuck on that method forever. So for instance, I want to add a student. On the menu, I choose 1 and since var==1 is true, the method add_student is called. Once I am done adding a student, I AM NOT ABLE to come back to the menu. What I mean by this is that the line
System.out.println("Would you like to return to the Main Menu to perform more tasks....."); is not executed. What is the Flaw?
My goal is to first display the menu through the menu function, then ask the user if he/she wants to perform any more tasks. If he/she wants to, then by pressing 'Y' the menu should get displayed again and so on. If after any iteration the user wants to quit then he/she should either choose 7 as an option to quit or simply enter 'N' or any other valid character.
PS: This is my new attempt at the code, I decided to change the switch statement as I do not fully understand it.

Related

need help to re-run my main class without killing the program

So basically I'm trying to make a minigame only using IF statements and in a single class, and everything is working smoothly so far. My biggest issue is, the "back" prompt. I tried system.exit(0), but since it kills the program, that won't be an answer. my question is, how do you "re-run" the class? For instance, when you are in the "options" menu, how do you go back in the main menu?
import java.util.Scanner;
public class Main {
public static void main (String[]args)
{
//Main Menu Prompt.
System.out.println ("Welcome to my mini parkour game!");
System.out.println ("Decide which trick to use, and don't mess up!");
System.out.println ("Choose one: Play, Quit");
Scanner bruh = new Scanner (System.in);
String MainMenu = bruh.nextLine ();
// Quit Prompt.
if (MainMenu.equals ("Quit"))
{
System.out.println ("You have quit the game.");
System.exit (0);
}
// Play Prompt.
if (MainMenu.equals ("Play"))
{
System.out.println ("Proceed to level 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
Scanner playgame = new Scanner (System.in);
String LevelSelect = playgame.nextLine ();
if (LevelSelect.equals ("1"))
{ System.out.println("You have reached this block of code!");
}
}
//code block to remind that java is case sensitive.
else {
System.out.println("error, try picking one again. (case sensitive.)");
return new Main();
}
}
}
I wanted the output to be at the main menu prompt even when you are from the play prompt, without killing the program.
I believe a while loop controlled by your user input stored in a variable will do the magic. You will have to learn how to use while loops.
If you want to advance to a God-level Java programmer use enum where you define your states and then create inside while loop a state machine using switch-case.
I am too lazy to type a working code here from my phone but something like that on a high level:
enum State { PLAY, QUIT };
public static void main(String[] args) {
boolean runAgain=true;
State state;
while (runAgain) {
//get the input from user
//update state
switch(state) {
case PLAY :
// update state
break;
case QUIT:
// update STATE
break;
//case WHATEVERELSE...
default:
assert false : "never get here";
}
}
}
It is a bit of learning and reading java specs involved, but Hey, after doing that you'll be able to program a working algorithm for .... an ELEVATOR!
Good luck!

java currency calculator pausing swtich to give output back to user

first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.

Try-catch around a choice menu

I've made a choice menu in a while loop. To make sure that users put in a valid choice, i put the menu itself in a try catch block:
I want the user to get a new chance if an exception was caught, so I put the try-catch block in a while(true) loop. However, using this kind of loop, the part where the actions are coded becomes unreachable code.
Is there a way to do this better?
And an extra question, How do i prevent a user from entering a choice option that does not exist?
while (choice != 0) {
/* Ask for player's choice */
while(true) {
try
{
BufferedReader menuInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Please choose between the following options:'");
System.out.println(" (1) Make new animal");
System.out.println(" (2) Feed Animals");
System.out.println(" (3) Count animals");
System.out.println(" (0) Quit");
System.out.print("Enter your choice: ");;
choice = Integer.parseInt(menuInput.readLine());
} catch (NumberFormatException ex) {
System.err.println("Not a valid number");
} catch (IOException e) {
System.out.println("Failed to get input");
}
}
// first choice option:
if (choice == 1) {
//actions
}
// second choice option:
if (choice == 2) {
//actions
}
// third choice option:
if (choice == 3) {
//actions
}
}
System.out.print("Thank you for playing!")
The very simplest way of doing it is to set a boolean flag above your loop:
boolean waitingForAnswer = true;
and then just change your while loop condition to while(waitingForAnswer) and set waitingForAnswer to false after one has been accepted.
You can then use that same structure to prevent them entering 5, or whatever. Simply tag an if on the end there that checks if the value is an accepted one, if it isn't, don't change waitingForAnswer
EDIT:
Incidentally, your string of if statements at the bottom isn't terribly efficient. If the user inputs "1" then the if (choice==1) block will trigger and it will then go on to check if it equals 2, if it equals 3, etc when we know for a fact it won't. Use else if there.
Another EDIT:
Also, create your input stream reader outside of the loop. Currently you're creating a new one each time the loop runs.

How to ask user if he/she wants to quit the program and print out the thank you message in Java

I am taking the first Java class and working on my second project. The project is about creating an program as a network of rooms on a virtual three-dimensional work area. Each room provides a virtual environment that together can be assemble into a simulated or virtual world.
Basically, the beginning of the program, I used while loop, and at the end I want to ask user if he/she wants to quit the program, and print a thank you message. However, the while loop does not work. My program quit no matter I entered y or n. Below is my codes.
import java.util.Scanner;
public class Project
{
public static void main(String[] args)
{
Map map = new Map();
int floor = 0;
int row = 0;
int col = 0;
String input = " ";
Scanner scan = new Scanner(System.in);
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
String choice = "y";
while(!input.equalsIgnoreCase("quit"))
{
input = scan.nextLine().toLowerCase();
// My codes are here
if (input.equals("south")
{statement}
else
System.out.println("You can't go that way.");
else if (input.equals("quit"))
{ // See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
// if user enters other words than quit
else
System.out.println("I don't recognize the word '" + input +"'");
}
System.out.println("Thank you for visiting L.A Underground.");
}
}
When I typed "quit" the console printed the message: "Do you wish to leave the Underground? (Y/N)? >". I tried Y/N (y/n) the program terminated. Any help is appreciated. Thank you.
Updated: Sorry for the confusion. What I wanted the program to run is when the user types "quit", the message will print out "Do you wish to leave the Underground (Y/N)?>?" , and if the user types "hello", the message will be "I don't understand the word 'hello'". And when the user type y, the program will quit, otherwise (type n), the program will start over again.
Ask for user input inside of your loop. If input.equalsIgnoreCase("quit"), then prompt the user an "are you sure" message. If the input.equalsIgnoreCase("y"), then break the loop, otherwise, keep going.
Scanner scan = new Scanner(System.in);
String input;
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
while (true) {
input = scan.nextLine();
if (input.equalsIgnoreCase("quit")) {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
if (scan.nextLine().equals("y")) {
break;
}
}
// input wasn't "quit", so do other stuff here
}
System.out.println("Thank you for visiting L.A Underground.");
Your code loops until it gets "quit" ... then asks for "yes/no" ... then simply exits, regardless.
You need to change your loop, so that it includes BOTH "MY CODES HERE" AND the "quit y/n" check.
EXAMPLE:
...
boolean done = false;
while(!done) {
//MY CODES ARE HERE
if (input.equalsIgnoreCase("quit") && getYesNo ()) == 'y') {
done = true;
}
}
"getYesNo()" is a method you write. For example:
char getYesNo () {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
String line = scan.nextLine();
return line.charAt(0);
}
In the code you've posted, your loop is being controlled by the condition !input.equalsIgnoreCase("quit"). That is, if input is "quit", the loop is terminated.
But the following block is executed only if input is "quit":
if (input.equals("quit"))
{
// See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
So if this block is executed, !input.equalsIgnoreCase("quit") evaluates to false and the loop is terminated. And that's not what you want.
Now that you know what's wrong, fixing it is easy. Check the value of choice in the above if block: if choice is not yes, don't quit i.e. reset input to a default value.
I've pasted the working code here on pastebin.

Java: User Input - Scanner - Program Hangs After Second Input

I'm making a console-based game of black jack that prompts the user asking him/her if he/she wants to: 'h' for hit, 's' for stay, or 'q' for quit. I'm using the Scanner class to receive input from the user in a while loop. The code works the first time it prompts the user and receives input, but it never works the second time. After the second prompt comes up, no matter what the user types, the program just waits and does nothing even though it's still running. I've been trying to get this to work for hours and have read the Java Docs, many SO questions, etc. Here's the relevant code:
public void gameloop() {
while (thedeck.cards.size() >= 1) {
prompt();
}
}
public void prompt() {
String command = "";
Boolean invalid = true;
System.out.println("Enter a command - h for hit, s for stay, q for quit: ");
Scanner scanner = new Scanner(System.in);
while (invalid) {
if (scanner.hasNext()) {
command = scanner.next();
if (command.trim().equals("h")) {
deal();
invalid = false;
} else if (command.trim().equals("s")) {
dealerturn();
invalid = false;
} else if (command.trim().equals("q")) {
invalid = false;
System.exit(0);
} else {
System.out.println("Invalid input");
scanner.next();
}
}
}
scanner.close();
}
Here's what the code outputs:
Dealer has shuffled the deck.
Dealer deals the cards.
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Enter a command - h for hit, s for stay, q for quit:
h
Dealer deals you a card:
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Queen of Hearts: 10
Enter a command - h for hit, s for stay, q for quit:
h (Program just stops here, you can keep entering characters,
but it does nothing even though the code is still running)
Any idea as to what's going wrong would be greatly appreciated. I also realize the while loop is a little ugly, but I just want to get this program in working condition before I start to revamp any code.
From the documentation for Scanner.close:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Here you close your scanner, and this causes System.In to be closed, which means you can't read any more input:
scanner.close();
It is better to open the scanner once and reuse it. Close it only when are sure you have finished reading all input, or are closing your application.

Categories

Resources