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.
Related
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);
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();
}
}
}
}
I want the program to retry the "try" part of the code every time the input is incorrect and throws an error(which is solved with an exception).
My code looks like this:
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
}catch(Exception e){
System.out.println("Incorrect input!");
My "makeHumanMove" function checks, if the number is from 1 to 3.. But if the user inserts a letter, it would throw an error and if it happens, I want the program to ask for another input until the user inserts a correct input.
I've tried while and for loops but I keep messing up. Any ideas?
How's about this code:
while (true) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
break;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Make sure that your makeHumanMove(enteredNumber); throws new Exception();
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
inputIsCorrect = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
This, of course, assumes that your makeHumanMove method throws an exception.
If I was doing this, I don't think I would be using exceptions. My code would be more like ...
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
inputIsCorrect = makeHumanMove(enteredNumber);
}
I'd change the makeHumanMove return a value that indicates whether the the inout is valid or not, rather than using exceptions. ( Can't remember if scanner.nextInt() throws exception .... )
Use a boolean value outside, set it to true at the end of the try block. Then you can test for it using a while loop.
int enteredNumber;
boolean correctNumber = false;
while (!correctNumber) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
correctNumber = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Note that you should not use exceptions at all to report incorrect input. You should test for incorrect input and abort early. You should also consider if makeHumanMove should actually be part of the try/catch block; input validation should not be part of the business logic of your application.
final int number;
System.out.print("Enter a number from 1 to 3: ");
while (true) {
int enteredNumber;
try {
enteredNumber = userInputScanner.nextInt();
} catch (Exception e) {
System.out.print("Not a number, enter a number from 1 to 3: ");
userInputScanner = new Scanner(System.in);
continue;
}
if (enteredNumber < 1 || enteredNumber > 3) {
System.out.print("Incorrect number, enter a number from 1 to 3: ");
continue;
} else {
number = enteredNumber;
break;
}
}
makeHumanMove(number);
I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}
I need help on how to use for-loops in Java
This is an assignment for class, so I'd rather just be pointed in the right direction instead of given an answer.
"List of valid seven dwarfs: Sleepy, Bashful, Doc, Sneezy, Happy, Grumpy, Dopey
Pool of random characters, non-valid Dwarfs: Lion-O, Cheetara, Panthro, Tigra, Snarf, Donald Duck, Mickey Mouse, Minnie Mouse, Goofy, Heathcliff, Huey, Dewey, Louie, Scrooge McDuck,
Declare these variables:
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
Print a list of three choices to the console. Ask the user to pick the correct dwarf of the three choices.
The list of three choices will include two names from the random characters list and one name from the seven dwarfs.
You will create a switch statement to handle the choice selection
When the wrong case is selected then decrement the int variable called counter and print to the console “wrong selection”
When the correct case is selected then change the corresponding boolean variable to true (ie.. firstSelection, secondSelection, etc) and print to the console “Hi Ho, you picked the correct one”
The default case will print a statement to the console “invalid selection”
Create a loop that will perform this seven times until you covered all seven dwarfs.
Use a for loop
Recreate the loop again using a do-while loop
Recreate the loop again using a while loop
At the end, create an if-else statement. This statement will have short circuit &&’s that will test all of the Boolean variables. If true, print a statement to the console “You earned a gold star!”. Else, print a statement to the console “You did not get all correct”. "
I completed the previous assignment, which was just this specification without the loops, with no problem. However I really don't understand how the professor wants us to integrate the loops into the problem. The only thing I can think of is that he wants up to create a loop seven times that somehow asks about a different dwarf each of the seven times. Is that even possible? Can you change the content of the loops as you are running through it? I feel like I am just not even thinking about this correctly.
Here is my code from the previous assignment, sans loops:
import java.util.Scanner;
public class SevenDwarfs {
public static void main(String[] args) {
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Sleepy");
System.out.println("2 Lion-O");
System.out.println("3 Cheetara");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hi Ho, you picked the correct one");
firstSelection = true;
break;
case 2:
System.out.println("Wrong selection");
--counter;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Panthro");
System.out.println("2 Bashful");
System.out.println("3 Tigra");
Scanner input2 = new Scanner(System.in);
int choice2 = input2.nextInt();
switch (choice2) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
secondSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Snaf");
System.out.println("2 Doc");
System.out.println("3 Donald Duck");
Scanner input3 = new Scanner(System.in);
int choice3 = input3.nextInt();
switch (choice3) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
thirdSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Mickie Mouse");
System.out.println("2 Sneezy");
System.out.println("3 Minie Mouse");
Scanner input4 = new Scanner(System.in);
int choice4 = input4.nextInt();
switch (choice4) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fourthSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Heathcliff");
System.out.println("2 Happy");
System.out.println("3 Goofy");
Scanner input5 = new Scanner(System.in);
int choice5 = input5.nextInt();
switch (choice5) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fiveSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Huey");
System.out.println("2 Grumpy");
System.out.println("3 Dewey");
Scanner input6 = new Scanner(System.in);
int choice6 = input6.nextInt();
switch (choice6) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sixSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Scrooge McDuck");
System.out.println("2 Dopey");
System.out.println("3 Louie");
Scanner input7 = new Scanner(System.in);
int choice7 = input7.nextInt();
switch (choice7) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sevenSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
if (firstSelection == true && secondSelection == true
&& thirdSelection == true && fourthSelection == true
&& fiveSelection == true && sixSelection == true
&& sevenSelection == true) {
System.out.println("You earned a gold star!");
} else {
System.out.println("\nYou did not get all correct.");
}
}
}
The fact that you realized you might be thinking about the concept incorrectly and asked for help is a good thing.
Read the following to get familiar with loops in Java.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To answer your question, yes, you can change the content of a loop as you run it. That's what variables are for. You can modify their values as your program runs. Look at this sample. The variable i increments with every iteration of the loop. The variable outsideLoop also changes inside the loop. Play with this and you'll start to understand.
class ForDemo
{
public static void main(String[] args)
{
int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
outsideLoop += i;
System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);
}
}
You've got a good starting point for the process of printing the selection, getting user input, and validating user input. Repeat that chunk (in a loop) 7 times.