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

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();
}
}
}
}

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()
}

Understanding Java while loops

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');

Java try catch for do while loop not looping

I was having some problem when trying to do a try catch for do while loop:
try{
do {
System.out.println("Enter your option: ");
choice = sc.nextInt();
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
} while (choice != 6);
}catch(InputMismatchException e){
System.out.println("Please enter option between 1-6.");
}
What I am trying to do for the do while loop is when user entered anything other than 6 which is terminate, it will keep prompting for user input. For each case, it will go to certain method.
Then, I tried to do a try catch for InputMismatchException because my Scanner is taking integer from user input. However, after I entered alphabet instead of integer, the program just terminated itself. I am trying to do like when user entered alphabet, it will keep on prompting user for correct input.
Any ideas? Thanks in advance.
I was thinking if I should make another do while to wrap the entire try catch?
Do like :
try {
choice = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("Please enter option between 1-6.");
sc.next();
continue;
}
If user enters a invalid input it will go to the catch block and will continue the loop. Remove the outer try catch block. Its not required
To handle characters and and invalid numbers you could do something like this:
do {
System.out.println("Enter your option: ");
try{
choice = sc.nextInt();
catch(InputMismatchException e){
choice = 0;
sc.next();
}
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Please enter option between 1-6.");
break;
}
} while (choice != 6);

Loop back to program after an exception is thrown

public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
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:
System.out.println("Invalid Entry");
throw new Exception();
}
} catch (Exception e) {
System.err.println("Enter Correct Input");
return;
}
} while (true);
}
I am trying to make it when users enter incorrect input type like a letter , the exception is caught and then returns back to the menus, right now it catches the exception but it doesnt stop running I have to force stop the program. So I added a return but that just displays the exception error and stops, how can I make it return back to the menus?
That is because you're returning from the method itself in the catch block.
And Do not throw exceptions like that. Just use some boolean to know if the choice is valid and loop until the choice is entered correctly.Prefer not to use while(true), instead rely on a boolean flag everytime like below,
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
int Choice = 0;
boolean isValidChoice = false;
do{
isValidChoice = false;
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");
if(Option.hasNextInt()){
Choice= Option.nextInt();
isValidChoice = true;
}
switch (Choice)
{
case 1:
CreateAccount();
break;
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:
isValidChoice = false; //if invalid choice, then set flag to loop
System.out.println("Invalid Entry");
}
} while (!isValidChoice);
}
Move the "try {" after the "System.out.println("Please choose");" line.
you just need to remove the return in the catch. also just as a tip, you can get rid of the do while and just have a while loop, because the loop is never ending.
} catch (Exception e) {
System.err.println("Enter Correct Input");
}
Okay so I'm pretty sure this should work:
Create a boolean value outside of while loop that is holds if there was a valid input
boolean validInput = true;
In default set this value to false (meaning there is an invalid input)
default:
System.out.println("Invalid Entry");
validInput = false;
throw new Exception();
Make sure the catch statement is still in the do loop because the throw clause will halt normal execution and transition into exception execution. Next the while tester will test if there was a valid input
while(!validInput)
Lastly go up to the top of the do loop and set validInput to true. This will make it so that each time you clear the previous incorrect input.
This should work.

How to make this program go back to prompt until the user exits

While writing code for my program I thought of testing the first part before moving on and writing the operations. Although I have the user input, but I want the options to be displayed after each operation (add, deltete..) is done untill the users presses exit. How do I modify my code to do it?
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Getting ready to Add a Record ");
//set();
break;
case 2:
System.out.println("Getting ready to Delete a Record ");
//delete();
break;
case 3:
System.out.println("Getting ready to Update a Record ");
//update();
break;
case 4:
System.out.println("Here is your record ");
//display();
break;
case 5:
System.out.println("Out we go.");
System.exit(0);
//exit();
break;
default:
System.out.println("Try again");
break;
}
} while ( choice > 5 || choice < 1 );
}
}
Simply change your while condition to:
} while ( choice > 0 && choice < 5 );
First make sure your scanner really has an int, use sc.hasNextInt() to validate the user entered a number. To end the do/while loop at "5.Exit", just have it like do{...}while(choice!=5). Code below is not tested.
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n 5.Exit");
System.out.println("Enter your Choice : ");
choice = -1;
Scanner sc = new Scanner(System.in);
// validate the next thing in your scanner is an int
// otherwise, sc.nextInt() might cause an exception
if (sc.hasNextInt()){
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Getting ready to Add a Record ");
// ...
break;
case 2: System.out.println("Getting ready to Delete a Record ");
// ...
break;
case 3: System.out.println("Getting ready to Update a Record ");
// ...
break;
case 4: System.out.println("Here is your record ");
// ...
break;
case 5: System.out.println("Out we go.");
// skip System.exit(0), your main method ends
// automatically when you leave your do/while loop
break;
default: System.out.println("Try again");
break;
}
}
// if choice == 5 it ends, otherwise, starts over...
} while ( choice != 5 );
}
}
Although I have the user input, but I want the options to be displayed
after each operation (add, deltete..) is done untill the users presses
exit.
You can set int flag=0; and when user selects exit option set flag to 1 to tell loop to exit.As of now you are already breaking out for number > 5 or < 1 in default case so no need to put that condition in while.
int flag=0;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=1;//Set flag to 1 if user enters 5
break;
...
} while ( flag!=1 );//Exit the loop when flag==1
//Or directly while ( choice!=5 );
Serious EDIT
As Java Programmer I should probably suggest you to use boolean primitive type for flagging.
boolean flag=true;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=false;//Set flag to 1 if user enters 5
break;
...
} while (flag);//Exit the loop when flag==false
One More thing:
Surround code with try-catch to leave out invalid inputs and prompt again for input.
Most of the times it's not recommended to swallow the Exception.
do{
try{
....//Your Switch case
}catch(InputMismatchException e){}
} while (choice !=5);//But remove System.exti(0); from your switch statement
Simply make your while loop as:
} while ( choice!=0 );(The Wrong one)
Correction:
} while(choice!=0 && choice<=5)

Categories

Resources