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.
Related
Good morning everyone... I am wondering where to put the try-catch block for not integer Input(InputMismatchException) to work in this code,
If I put it here doesn't work, if I put it before while, it's an infinite loop, if you can explain where and why it will be perfect, thank you for your time.
public void additionalIngredients() {
Set<Integer> set = new HashSet<>();
boolean flag = false;
while (!flag) {
System.out.println("Enter your choice for extra toppings ");
int choices = scanner.nextInt();
scanner.nextLine();
try {
switch (choices) {
case 0:
System.out.println("Done");
flag = true;
break;
case 1:
if (!set.contains(choices)) {
double extraSauce = 1.2;
setAdditionalStuff(getAdditionalStuff() + extraSauce);
System.out.println("Extra sauce added on your pizza \n");
break;
} else {
System.out.println("You already added extra sauce, please consider to add something else");
break;
}
case 2:
if (!set.contains(choices)) {
double extraCheese = 2.3;
setAdditionalStuff(getAdditionalStuff() + extraCheese);
System.out.println("Extra cheese added on your pizza \n");
break;
} else {
System.out.println("You already added extra cheese, please consider to add something else");
break;
}
case 3:
if (!set.contains(choices)) {
double largeDough = 0.7;
setAdditionalStuff(getAdditionalStuff() + largeDough);
System.out.println("Your pizza has a large Dough \n");
break;
} else {
System.out.println("Your pizza has already a large dough, consider something else");
break;
}
}
set.add(choices);
} catch (InputMismatchException e) {
System.out.println("Please enter an integer!");
}
}
}
There are may ways to go about this. Always strive for solutions that make your code easier to read and understand.
One way to do that: you could for example create another helper method fetchSelectionFromUser() that does one thing only: loop (with try catch) until the user entered a valid number.
One guiding rule is the single layer of abstraction principle. And that tells you that having a-switch-in-a-try-in-a-loop isn't the way to go. As said, you could go for a loop that simply calls two methods: one that fetches the input, and another one that processes it.
This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 3 years ago.
I'm a new programmer. I'm coding a user menu and I've a question on the do-while loop. When main() calls my first method containing my first loop it works as expected. However, when the user selects makes a choice and customerMenu() is called, it prints the menu 3 times. Why is this? Is there a mistake in my code?
public class Runner {
public static void main(String[] args) {
Menu m = new Menu ();
m.mainMenu();
}
}
public class Menu {
private char choice;
public void mainMenu () {
try {
do {
System.out.println("Create Order");
System.out.println("View Orders");
System.out.println("Customers");
System.out.println("Employees");
choice = (char) System.in.read();
} while (choice < '1' || choice > '4');
System.out.println("\n");
switch (choice) {
case '1':
System.out.println("Create Order page");
break;
case '2':
System.out.println("View Orders page");
break;
case '3':
customerMenu();
//System.out.println("Customers page");
break;
case '4':
System.out.println("Employees page");
break;
}
} catch (Exception e) {
System.out.println("Error");
}
}
// Do loop prints 3 times
public void customerMenu () {
try {
do {
System.out.println("Add a Customer");
System.out.println("Edit a Customer");
System.out.println("Delete a Customer");
choice = (char) System.in.read();
} while (choice < '1' || choice > '3');
System.out.println("\n");
switch (choice) {
case '1':
System.out.println("Add a Customer action");
break;
case '2':
System.out.println("Edit a Customer action");
break;
case '3':
System.out.println("Delete a Customer action");
break;
}
} catch (Exception e) {
System.out.println("Error");
}
}
}
There are no problems with the logic of your program but instead of using System.in.read () use either Scanner or BufferedReader. I can only guess that the three other characters that System.in.read () read are the null byte, line feed, and carriage return.
I just tried out the code (link to test env) and for me the menu is printing two times, not three.
The reason it prints twice is because System.in.read() reads in the next byte of data. When you type '3' and hit enter, that sends two bytes of data to the input stream. One byte for the 3 and one byte to indicate 'newline'.
The first time the do-while loop is entered, it reads in the 'newline' byte. That causes the loop to run a second time. The second time around, there's no more bytes to read so it waits for input for user.
Hi there i found your're mistake, i am not good with java. hmm maybe just printing the choice variable you will find your answer.
in mainmenu you have the choice variable and when you called customerMenu on the do while loop the choice variable is read again.
solution create another variable for customerMenu.
My code below is looping twice. The 1st while loop before it asks for user input (to make a choice). I made it simpler by putting choice default is "N".
So it hits the if statement and begins the 2nd while loop. Now it asks the user for another choice. The user can only enter "A" as anything else will error trap. The user enters "A" and gets prompted to add a number (the variable num = 0). User enters a number.
The if statement closes, and the 2nd while loop comes back to the top, only it doesn't stop when the user is asked for a choice. Instead, it continues through the loop, hits the else statement, then comes back to the top of the 2nd while loop again and presents the user with a prompt for a choice.
Code Updated with More Information
while (true) { // 1st while loop
choice="N";
if (choice.equalsIgnoreCase("N")) {
while (true) { // 2nd while loop
System.out.println("|-|-| Add Number [A] Go Back [B]");
System.out.println("NUMBER: "+num);
System.out.print("Choice: ");
choice = c.nextLine();
if (choice.equalsIgnoreCase("A")){
System.out.print("Add: ");
num = (c.nextInt() + num);
System.out.println("");
}
else if (choice.equalsIgnoreCase("B")){
break;
}
else {
System.out.println("ERROR 19: Invalid response");
System.out.println("");
}
}
}
}
I have tried using different variables for choice. It did not work. I think I may need to try catch just below the 2nd while loop (before the user is prompted for a number), but that's only a idea. My question would be, why is this happening? And if possible, how can I fix it?
In your code while(true) will keep looping indefinitely. Either change the condition from always true to something which is conditionally true (using an if condition inside the while loop or a for loop). Or use a mix of break, return and continue when you think looping should stop.
Add a break statement in both if and else statement :
if (choice.equalsIgnoreCase("A")){
System.out.print("Add: ");
num = (c.nextInt() + num);
System.out.println("");
break;
}
else {
System.out.println("ERROR 19: Invalid response");
System.out.println("");
break;
}
I think you should change your loop. I suggest loop with like this :
boolean finished = false;
while(!finished) {
...
choice = c.nextLine();
if (choice.equalsIgnoreCase("A")){
System.out.print("Add: ");
num = (c.nextInt() + num);
System.out.println("");
} else if (choice.equalsIgnoreCase("Exit")) { //You can change this whatever you want
finished = true;
} else if (...){
... //another choice
}
else {
System.out.println("ERROR 19: Invalid response");
System.out.println("");
}
}
The Scanner#nextLine consumes the full line (hence "next line") of the user input. That's why you never get a repeated loop while using nextLine. The Scanner#nextInt does not, and the last newline character is consumed the next time Scanner#nextInt is called.
To answer my question:
if (choice.equalsIgnoreCase("A")){
System.out.print("Add: ");
num = (c.nextInt() + num); //Prompts user for input (number)
c.nextLine(); // Consumes the last newline character
System.out.println("");
}
else if (choice.equalsIgnoreCase("B")){
break;
}
else {
System.out.println("ERROR 19: Invalid response");
System.out.println("");
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
As answered from here: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
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")) {
...
}
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.