Repeating to the main menu upon a specific user input - java

I am trying to create a simple program in java where the user can input some lines and then save it and then load the data from the saved file.
Currently, i have the basic outline of the program, but am stuck on the first stage where the user enters his data, then wishes to return to the main menu for another selection.
Code:
import java.io.*;
import java.util.*;
public class Datafile{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Kence\\workspace\\Java 8 - Beyond the Basics - Working Files\\Practice Programs\\src\\Practice Data Edited",true));
String data = null;
String dataEntered = null;
int menuChoice = printMenu();
switch(menuChoice){
case 1:
System.out.println("Please enter a line of data");
dataEntered = input.nextLine();
if(Integer.parseInt(dataEntered) == 0){
System.out.println("OK");
//printMenu(); <--- Qn 1. Where i am stuck
return;
}else{
System.out.println(dataEntered);
}
//Why this does not recognize "quit" when entered
/*if(dataEntered == "quit"){ <--- Qn2. Where i am stuck
System.out.println("OK");
}else{
System.out.println("Error");
}*/
data += dataEntered;
System.out.println("Data entered.Please enter the next line of data or press quit to exit back to the main menu.");
break;
case 2:
System.out.println("2 Entered");
break;
case 3:
System.out.println("3 Entered");
break;
case 4:
System.out.println("4 Entered");
break;
}
input.close();
}
public static void printStars(){
for(int i = 0; i<66 ; i++){
System.out.print("*");
}
System.out.println();
}
public static int printMenu(){
printStars();
System.out.println("System Started");
printStars();
System.out.println("Enter 1 to input a new line of data");
System.out.println("Enter 2 to list all data");
System.out.println("Enter 3 to save existing data");
System.out.println("Enter 4 to load data");
printStars();
return Integer.parseInt(input.nextLine());
}
}
QN 1
In the code example above, when the user enters 0, the i can run printMenu(), but am unable to take any further action after that. I would like to be able to select the options 2,3 or 4 after the user enters 0.
Edit: printMenu works fine on the initial start-up, it's after i enter 1,input data, then press 0, that the new printMenu() does not work as i'm not actually testing the input with a switch statement. I can't figure out a way to run printMenu() again at this point without nesting another switch statement, and another switch statement after that and so on..
Qn2.
When i enter quit, the program does not output "OK", but outputs ERROR instead. I don't understand why this is happening as i am comparing the input (which is a string) with the string "quit", yet somehow the program does not recognise both strings as equals?
I would appreciate any clarifications and advice.
Thanks!

Qn1: Here's another way to retrieve the input, hopefully it will solve the problem:
public static int printMenu(){
...
intInput = input.nextInt();
input.nextLine();
return intInput;
}
Qn2: The == comparator is not used for strings. Try this instead:
if(dataEntered.equalsIgnoreCase("quit")) {
...
}

Related

How do I go back to the menu after taking several questions?

I am currently creating a program where the user enters a specific set of questions. And the program must go back to the menu after completely answering all questions. How should I do it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("""
\n \nAre you ready to take the quiz?
Enter "Y" to proceed or "N" to exit the program:""");
String TakeQuiz = input.nextLine();
if (TakeQuiz.equalsIgnoreCase("Y"))
do {
//blocks of code
}
}
}
System.out.println("Do you want to take the quiz again?");
String RetakeQuiz = input.nextLine();
while (RetakeQuiz.equalsIgnoreCase("Y")) ;
else {
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
There are many ways to achieve what you want, I would not clutter the main method and break the code to another function and loop there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for(;;)
takeQuiz();
}
public static void takeQuiz(){
Scanner input = new Scanner(System.in);
System.out.print("\n \nAre you ready to take the quiz?" +
"Enter \"Y\" to proceed or \"N\" to exit the program:");
String takeQuiz = input.nextLine();
if (takeQuiz.equalsIgnoreCase("Y")) {
System.out.println("Running code...");
System.out.println("Question 1");
System.out.println("Question 2");
System.out.println("Question 3");
}
// retake
if (takeQuiz.equalsIgnoreCase("R")){
takeQuiz();
}
if (takeQuiz.equalsIgnoreCase("N")){
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
Notice the escape character for quotes \" and the + for multiline Strings
Java 15 and beyond allows triple quotes as Java Text Blocks
so your String message should be valid
The basic structure is something like this:
boolean continueWithQuiz = true;
while (continueWithQuiz) {
// Put the code here for handling the quiz
...
// Should we keep going?
System.out.println("Do you want to take the quiz again?");
String retakeQuiz = input.nextLine();
continueWithQuiz = retakeQuiz == "Y";
}
One more comment. Please follow Java naming standards. Class names begin with an upper case letter. Constants should be ALL_CAPS. Everything else is in lower case.

How to make Image pop out of console (Eclipse/Java)

My tutor is having issues directing me with the problem below. Hoping I can find some answers from the community.
I am trying to add an image pop out to a simple console application, and from research it would appear I need to use JImage/JFrame (I think). However, my tutor believes I can use the below code (which doesn't work when I use it, and tutor has no idea why not).
System.out.println(new Picture(FileChooser.pickAFile()).show()).
This returns "Picture can not be resolved to a type".
I believe it is supposed to allow me to select a picture, but it doesn't. Also it doesn't matter whether I put the destination of the picture directly in to the code either.
Simply put, I need a picture to print out to screen/new window when an option is selected from my menu, if anyone can help with this, it would be great!
Full code below (section is down near the bottom / loadMuseums method)
package CWK2;
//IMPORTS REQUIRED FOR COMPILATION
import java.util.Scanner;
public class menuSystem {
public static void main(String[] args) throws Exception {
boolean incorrect = false; // SETS THE VARIABLE FOR THE WHILE CONDITION BELOW
String input = "";
while (incorrect == false) { // WHILE STATEMENT TO MAKE THE BELOW A
// REPEATING MENU IF WRONG INPUT
incorrect = true; // TO INITIALLY MAKE THE LOOP ONLY RUN ONCE (E.G CORRECT INPUT)
// PRINTING OF THE MENU
System.out.println("**WELCOME TO THE TOUR GUIDE**");
System.out.println();
System.out.println("1. Museums");
System.out.println("2. Eating Out");
System.out.println("3. Shopping Centres");
System.out.println("4. Historical / Places of Interest");
System.out.println();
System.out.print("Please enter your choice (1/2/3/4) : ");
Scanner choice = new Scanner(System.in);
input = choice.next();
System.out.println();
switch (input) { // SWITCHES FROM USER'S INPUT
case "1": {
loadMuseum();
choice.close(); // CLOSES THE SCANNER AND STOPS MENU REPEAT
break;
}
case "2": {
loadEateries();
choice.close(); // CLOSES THE SCANNER AND STOPS MENU REPEAT
break;
}
case "3": {
loadShops();
choice.close(); // CLOSES THE SCANNER AND STOPS MENU REPEAT
break;
}
case "4": {
loadHistoricals();
choice.close(); // CLOSES THE SCANNER AND STOPS MENU REPEAT
break;
}
default: { // DEFAULT METHOD USED FOR INCORRECT INPUT (ANYTHING
// OTHER THAN 1-4)
System.out.println("");
System.out.println("You have entered an incorrect option.");
System.out.println("You will need to try that again. Remember 1-4 are your choices.");
System.out.println("");
incorrect = false; // KEEPS THE REPEATING MENU GOING
break;
}
}
}
}
public static void loadMuseum() {
//insert pic
System.out.println(new Picture(FileChooser.pickAFile()).show()).
System.out.println("");
System.out.println("");
//insert pic
System.out.println("");
System.out.println("");
}
private static void loadEateries() {
//insert pic
System.out.println(""); //insert bio
System.out.println("");
//insert pic
System.out.println("");
System.out.println("");
}
private static void loadShops() {
//insert pic
System.out.println(""); //insert bio
System.out.println("");
//insert pic
System.out.println("");
System.out.println("");
}
private static void loadHistoricals() {
//insert pic
System.out.println(""); //insert bio
System.out.println("");
//insert pic
System.out.println(""); //insert bio
System.out.println("");
}
}
In order to display a picture you need a JFrame or some other kind of container. System.out.println() prints out to the console which only displays text.
You can find how to do that here: Displaying Image in Java

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.

java simple UI loop, can't find bug

I've written the UI class below and it's basically just a simple loop that calls a couple of methods in the class, console based ui.
The user is supposed to be able to select from 1 of 6 menu choices. Now, the selection input from the user must be of type int. I surrounded the selection code with a try {} catch{} to handle an invalid, non-int, input.
So when I test it everything works fine. Right now if the user inputs a valid selection, an int of 1,2,3,4,5, or 0 then it's stuck in the while loop. This isn't the bug I just haven't implemented the menu choices yet.
The bug appears when the user enters a non-int invalid input. Maybe I have done something funky with the exception handling, not sure, but if you put in an invalid input it just loops endlessly as if an invalid input is being entered over and over even if I input nothing. It seems like it's getting input from somewhere else but I have no idea what could be sending input to the Scanner.
I know I have other Scanner objects but they're not even in the same class and aren't connected to this class at all yet. I was hoping someone else could take a look at it and maybe tell me what I've got wrong.
class UI{
private Scanner userInput;
private String fileName;
private Performance perf;
private Menu menu;
private int selection = -1;
public UI(){
userInput = new Scanner(System.in);
setFileName();
initializePerformance();
initializeMenu();
loopUI();
}
void setFileName() {
System.out.print("\nEnter the performance file name: ");
try{
fileName = userInput.next();
} catch (Exception e){
System.err.println(e.getMessage());
setFileName();
}
}
void initializePerformance(){
perf = new Performance(fileName);
}
void initializeMenu(){
this.menu = new Menu();
menu.addItem("Rows");
menu.addItem("Show Row");
menu.addItem("Seat Status");
menu.addItem("Buy Ticket");
menu.addItem("Return Ticket");
menu.addItem("Exit and Save");
}
void showMenu(){
menu.showMenu();
}
void selection() {
System.out.println("\nSelection[1,2,3,4,5,0]: ");
try{
this.selection = userInput.nextInt();
}catch(Exception e){
System.out.println("Invalid selection, try again.");
}
}
void loopUI(){
while(selection != 0){
System.out.println("\n" + perf.getName());
showMenu();
selection();
}
}
}
You'll have to add userInput.next() within the catch clause to consume the rest of the line after using userInput.nextInt().

Creating a console menu for user to make a selection

Doing a program in Eclipse with Java. What I want to do is when I execute the program I want present the user with a choice. I have all the calculations etc. done, I'm just unsure as to how to make this menu to offer the user choices. Example of what I'm looking for:
To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:
public static void main(String[] args) {
Data data = new Data();
data.menu(); }
}
For simplicity's sake I would recommend using a static method that returns an integer value of the option.
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
/***************************************************/
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Enter an original number");
System.out.println("2 - Encrypt a number");
System.out.println("3 - Decrypt a number");
System.out.println("4 - Quit");
selection = input.nextInt();
return selection;
}
Once you have the method complete you would display it accordingly in your main method as follows:
public static void main(String[] args) {
int userChoice;
/*********************************************************/
userChoice = menu();
//from here you can either use a switch statement on the userchoice
//or you use a while loop (while userChoice != the fourth selection)
//using if/else statements to do your actually functions for your choices.
}
hope this helps.
You can use a scanner to read input from System.in, as follows:
public static void main(String[] args) {
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
// Perform "original number" case.
break;
case 2:
// Perform "encrypt number" case.
break;
case 3:
// Perform "decrypt number" case.
break;
case 4:
// Perform "quit" case.
break;
default:
// The user input an unexpected choice.
}
}
Note that this will require the user to input a number and press enter, before continuing execution. If they enter invalid input, this will halt; if you want it to prompt them again, you will need to wrap this in a loop of some sort, depending on how you want the system to behave.
Scanner#nextInt may very well throw an exception, should the user input something that cannot be parsed to an integer. You can catch this exception and handle it appropriately. If the user enters an integer that is out of the range of valid options (i.e. it is not in the range of 1-4), it will fall to the default branch of the switch statement, where you can again handle the error case however you wish.

Categories

Resources