the following code terminate after try catch block catches exception.its not allowing me to make choice from the menu option. so my question is what changes do i have to make on this code so that i can loop back so that i can get user input again.
public class Main {
public static void main(String[] args) {
Modify modifyObj = new Modify();
int choice = 0 ;
Scanner input = new Scanner(System.in);
//begin loop
do {
try{
//display menu
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
choice = input.nextInt(); //gets user input
switch (choice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}// end of switch statement
break;
}//end oftry
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
continue;
}
}while (choice!=0); //loop until user exit 0.
}//end of main
}// end of Main class
Make sure choice isn't 0 before you continue;
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
choice = 1; // <-- not 0.
continue;
}
Note that you default choice to an initial value of 0.
You Could Use Methods
If you extracted your logic into one (or two) utility methods to display the menu and get the user's choice it would simplify things; something like
private static void showMenu() {
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
}
private static int getUserOption(Scanner input) {
while (true) {
showMenu();
if (input.hasNextInt()) {
int t = input.nextInt();
switch(t) {
case 0: case 1: case 2: case 3:
return t;
}
} else {
input.nextLine();
}
}
}
Then your main could invoke it like
public static void main(String[] args) {
Modify modifyObj = new Modify();
Scanner input = new Scanner(System.in);
int choice;
// begin loop
do {
choice = getUserOption(input);
if (choice != 0) {
System.out.printf("You chose %d.%n", choice);
}
} while (choice != 0); // loop until user enters 0.
}// end of main
Related
I have a project that I want it to go back to the first menu if it is selected from the second menu.
The following is just an example:
import java.util.Scanner;
public class SAMPLE {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
This is the first menu:
System.out.println("Enter choice: ");
System.out.println("1 = A");
System.out.println("2 = B");
int choice1 = input.nextInt();
do {
This is the second menu:
System.out.println("Another choice:");
System.out.println("1 = C");
System.out.println("2 = D");
System.out.println("3 = Go back");
int choice2 = input.nextInt();
switch (choice2) {
case 1: System.out.println("nice");
break;
case 2: System.out.println("nicee");
break;
If I selected 3, it should go back to the first menu but I don't know how.
case 3: System.out.println("How can I go back to the first menu? HELP!");
break;
}
} while (choice1 > 2);
System.out.println("END OF THE PROGRAM");
}
}
I would suggest splitting your code into functions.
Upon case 3 - You shall call your new function.
Something like this:
static int mainMenu(Scanner inputScanner)
{
System.out.println("Enter choice: ");
System.out.println("1 = A");
System.out.println("2 = B");
return inputScanner.nextInt(); //Assume valid input. you should add a valid check
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Choice1 = mainMenu(input);
do {
System.out.println("Another choice:");
System.out.println("1 = C");
System.out.println("2 = D");
System.out.println("3 = Go back");
int Choice2 = input.nextInt();
switch (Choice2) {
case 1: //DO Y
break;
case 2: //DO X
break;
case 3: Choice1 = mainMenu(input);
break;
}
} while (Choice1 > 2);
//END logic
}
Aha You want to go back to the first menu of choosing A and B in the process of choosing C and D!
There are many ways(such as use another method or recursion),
but I recommend this method which will be easier to understand now.
First, Let's check the code to organize what we want to do
<I changed it slightly to make it more recognizable! I'm sorry!>
import java.util.Scanner;
public class StackOver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
////main_menu///-Select A or B
System.out.println("Please input Enter Choice: ");
System.out.println("input '1' to Select A");
System.out.println("input '2' to Select B");
int choice1 = input.nextInt();
////////////////////////////
////second_Menu Choose C or D, or Back to main_menu
System.out.println("Another choice: ");
System.out.println("input '1' to Select C");
System.out.println("input '2' to Select D");
System.out.println("input '3' to Go back");
int choice2 = input.nextInt();
//According to 'choice2'
switch(choice2) {
case 1: System.out.println("nice, you Select C");
break;
case 2: System.out.println("nicee, you Select D");
break;
case 3: System.out.println("Now, you can go to Back");
break;
}
//I'm sorry, but I can't understand the meaning of
//'while (choice1 > 2);' ㅠㅅㅠ
System.out.println("END OF THE PROGRAM");
}
}
So the code above is the one you asked for, right?
There are so many ways to implement it in the direction you want.
Let's try to get it back to the main menu through the While statement you were trying to use.
The code progresses.
(1) Choosing A and B
(2) Choosing C and D or (1)
It consists of going to (1) or ending the program, depending on the result of (2).
how about use do{ }while(boolean);??
The process in do{} will continue until 'boolean' is false.
now We can change code in this way
import java.util.Scanner;
public class StackOver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int choice2 = 0; //init for NullPointerError
do {
//below do{
////main_menu///-Select A or B
System.out.println("Please input Enter Choice: ");
System.out.println("input '1' to Select A");
System.out.println("input '2' to Select B");
int choice1 = input.nextInt();
////////////////////////////
////second_Menu Choose C or D, or Back to main_menu
System.out.println("Another choice: ");
System.out.println("input '1' to Select C");
System.out.println("input '2' to Select D");
System.out.println("input '3' to Go back");
choice2 = input.nextInt();
//According to 'choice2'
switch(choice2) {
case 1: System.out.println("nice, you Select C");
break;
case 2: System.out.println("nicee, you Select D");
break;
case 3: System.out.println("Now, you can go to Back");
break;
}
}while(choice2 == 3);
//if choice2 == 3, then the progress of code return back to below 'do{'
System.out.println("END OF THE PROGRAM");
}
}
This is the result of the changed code.
I hope you understood it well and If there's anything that's hard to understand, please leave a comment!
I hope you have a pleasant and peaceful day today.😻😻
I have a question as to how I can perform several checks inside the switch-case? I need to do a couple of checks in case 2, but adding a second if block, my application does nothing, it just hangs. What was I wrong about?
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
In the second case statement, you should read the next input only once:
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String next = inputCommand.readLine();
if (next.equals("su")) {
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (next.equals("an")) {
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
}
Your first if statement is swallowing the input line, so the second if statement has nothing to read.
Just store the line after reading it once :
String readLine = inputCommand.readLine();
if (readLine.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (readLine.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
Everytime you do a inputCommand.readLine() the Programm waits for an input on your side. You can't compare a single input like you did in this example. The best way would be to save the input in a variable and then perform your checks. Something like this would work (not tested):
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String input = inputCommand.readLine();
if (input.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (input.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
Replace if with else if
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
I assumed this is a basic program for learning purposes so i tried to keep it simple.
1.Don't forget to close Scanner class.
2.always convert digit input to LowerCase(consider case of 'q' vs 'Q')
3.everytime you execute "scanner.nextLine()" your program will halt and wait for input from source(in that case System.in configured to take input from keyboard)
4.System.out.println will print '\n' to the screen at the end of its input causing it to create a new line, you can use this char inside your string to save code lines.
Complete Code:
import java.util.Scanner;
import java.io.IOException;
public class MyClass {
public static void ShowMenu()
{
System.out.println("\nInstruction:");
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println("q -- Quit Program");
}
public static void ProductMenu()
{
System.out.println("Select product to add into your basket");
System.out.println();
System.out.println("ba -- Basketball");
System.out.println("fi -- Fiat 500");
System.out.println("ip -- Iphone");
System.out.println();
}
public static void Exit(Scanner sc) {
sc.close();
System.out.println("You've exited the program. goodbye!");
System.exit(1);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String inputCommand = null;
while (true) {
ShowMenu();
switch (inputCommand = scanner.nextLine().toLowerCase()) {
case "1":
System.out.println("you entered 1");
break;
case "2":
ProductMenu();
inputCommand = scanner.nextLine(); //should block
if (inputCommand.equals("ba")){
System.out.println("Basketball added.");
}
if (inputCommand.equals("fi")){
System.out.println("Fiat 500 added.");
}
if (inputCommand.equals("ip")){
System.out.println("Iphone added.");
}
break;
case "q":
Exit(scanner);
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
}
I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}
Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)
As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
I am working on an example using a do-while loop and switch statement. What I basically need is to accumulate numbers and depending on user input either add, substract, multiply or divide (mini calculator type).
The problem is when I ask the user to go back to the main menu the program does not reset the value as it is before the loop. The result is always the previous result.
Here is the code, it will explain it better.
import java.util.Scanner;
public class SwitchLoopNumbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int numbers=0;
int result=0;
int option;
boolean quit = true;
String done="";
do{
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while(quit){
switch(option){
case 1:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if(numbers==0)
quit=false;
result +=numbers;
break;
case 2:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -=numbers;
if(numbers==0)
quit=false;
break;
}
}
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//I did reset numbers and result here to zero but it did not work
}
while("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
A couple things are going on here. To answer your question concisely, it's because you didn't reassign your variables before re-looping. Since you don't reassign result and quit, quit is false so it closes the loop, and result is unchanged so it then prints the same result. Try this:
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
I think it's the most straight-forward solution to your problem.
EDIT: I also wanted to add that using quit as the while condition seems a little counter-intuitive. If I saw a condition quit that was true, my assumption would be that it would break the loop, not continue it. You might make your code a bit clearer by designating more meaningful variable names. So instead of saying something like:
boolean quit = true;
while(quit) {
//do stuff
if (some_condition) {
quit = false;
//close loop
}
}
This may be a little clearer:
boolean quit = false;
while(!quit) {
//do stuff
if (some_condition) {
quit = true;
//close loop
}
}
Just a general suggestion.
You can try to call main() again, but I'm not sure if it will work, solution can be make your own method eg. init() - where you will set vars into init state, and eg. work(), what will be remaining code :D
EDIT: you can make it this way
import java.util.Scanner;
public class main {
//if you want work with result after user will write "y" in the end
static int result = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int option;
boolean quit = false;
String done = "";
//int result = 0; // if you want also init result
// menu
System.out.println("CALCULATOR MENU");
System.out.println("********** ****\n");
System.out.println("1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
// user menu input read
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
switch (option) {
case 1:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = true;
}
result += numbers; // result = result + numbers
}
break;
case 2:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -= numbers; // result = result - numbers
if (numbers == 0) {
quit = true;
}
}
break;
default:
System.out.println("Bad inpout");
break;
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//recursive call - run main() again
if (done.equals("y")) {
main(args);
} else {
System.out.println("Thank you for using calculator");
}
}
}
Im facing problem when i use to run this program.this is continuously repeating the case 1 .`
import java.util.Scanner; //importing
public class DynamicStackByArray { // name of class
private static String[] a;
private static int size;
public DynamicStackByArray(){} // end of the null constructor
public DynamicStackByArray(int capacity){
a=new String[capacity];
}// end of the parameterized constructor
private static String peek(){
if(size==0)
throw new IllegalStateException("Stack is Empty");
else
return a[size-1];
}// end of the displaying method
private static String pop(){
if(size==0)
throw new IllegalStateException("Stack is Empty...");
else{
String o=a[--size];
a[size]=null;
return o;
}
}// end of the pop method
private static void push(String o){
if(size==a.length)resize();
else
a[size++]=o;
}// end of the push method
private static void resize(){
String aa[]=a;
a=new String[1+aa.length];
System.arraycopy(aa, 0, a, 0, size);
aa=null;
}// end of the resize method
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of dynamic stack :");
int cap=in.nextInt();
DynamicStackByArray d=new DynamicStackByArray(cap);
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
int choice=in.nextInt();
while(choice!=-999){
switch(choice){
case 1:{
System.out.println("Enter your desire data");
System.out.println("Note that -999 will let u escape out of it... :)");
String input;
input=in.nextLine();
String as="-999";
if(!input.equalsIgnoreCase(as)){
d.push(input);
}// end of checker
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of case 1
case 2:{
System.out.println("Value "+d.peek()+" has been poped ");
d.pop();
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of the case 2
case 3:{
System.out.println("Value "+d.peek()+" has been peeked");
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of the case 3
default:{
System.out.println("Sorry this is a wrong choice...");
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of default
}// end of the switch statement
}// end of the repetation of the program
System.out.println("GOOD BYE... !!!");
}// end of the main method
}// end of the class
`
you forgot to ask scanner for input inside your loop. You can fix it :
int choice = 0;
while ((choice = in.nextInt()) != -999) {
//... your loop
}
One more important thing :
in case 1: when you read input=in.nextLine(); it will consume \n symbol that was used to terminate "1" input and your String input will be always empty string. (just put a breakpoint and verify it yourself)
Therefore, you have to add extra nextLine() statement inside case 1:
in.nextLine(); // read `\n` symbol;
String input = in.nextLine();
It is not executing just case1 all the time. The program is running correct. You just made mistake by take peek method in both cases, u should use pop method in case2 as u desired for.