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!");
}
Related
So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```
boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.
your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!
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);
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.
The code snippet below causes an endless loop, when I enter a character. That's really weird for me, for a wrong number it works fine, but when I am entering any character, it causes an endless loop.
boolean checkValue = false;
Scanner console = new Scanner(System.in);
while (!checkValue) {
System.out.println("Enter 1, 2 or 3");
try {
input = console.nextInt();
switch (input) {
case 1:
// code
checkValue = true;
break;
case 2:
// code
checkValue = true;
break;
case 3:
// code
checkValue = true;
break;
default: // when entered a wrong number
System.err.println("Wrong Input");
checkValue = false;
}
}
catch(Exception e) { // when entered a character
System.err.println("Wrong Input");
checkValue = false;
}
}
You need to check for the right type of the input, instead of trying to catch an exception. When you find the wrong input has been supplied, you have to consume the input in order to proceed to the next try. Like so:
public static void main(String[] args) {
boolean checkValue = false;
int input;
Scanner console = new Scanner(System.in);
while (!checkValue) {
System.out.println("Enter 1, 2 or 3");
// Check if we have an integer
if (console.hasNextInt()) {
input = console.nextInt();
switch (input) {
case 1:
// code
checkValue = true;
break;
case 2:
// code
checkValue = true;
break;
case 3:
// code
checkValue = true;
break;
default: // when entered a wrong number
System.err.println("Wrong Input");
checkValue = false;
}
}
else {
// when entered a character
System.err.println("Wrong Input");
// Consume the wrong input.
console.next();
checkValue = false;
}
}
}
You assign the input into one variable :
input = console.nextInt();
But the switch statement tests a different variable :
switch (auswahl) {
EDIT :
Add console.nextLine() to your exception handler, to consume the end of the current line, to allow the next nextInt to read from the next line.
What's "auswha1" ? Its value is not updated and your scanner is outside the loop.
Moreover, are you sure that you are testing a character in your switch ? It looks like an int.
Edit :
Instantiate a new scanner before calling nextInt, it should work :
try {
Scanner console = new Scanner(System.in);
int input = console.nextInt();
switch (input) {
...
Since you use console.nextInt(), you will read only integers on the input. Then, when you enter something which is not an int, you catch an Exception. There you need to consume the bad input, e.g. with a nextLine():
catch(Exception e) { // when entered a character
System.err.println("Wrong Input");
checkValue = false;
console.nextLine(); // <=== add
}
Then it works...
You probably get java.util.InputMismatchException after inputting any illegal character. It does not clear the input buffer, so calling nextInt() causes the same error etc.
Add console.next(); to the catch clause to skip the wrong character.
auswahl variable is not assigned with your input. Actually speaking this variable is not even in scene till you use it in switch.
boolean checkValue = false;
int input;
Scanner console = new Scanner(System.in);
while (!checkValue) {
System.out.println("Enter 1, 2 or 3");
try {
input = console.nextInt();
switch (input) {
case 1:
// code
checkValue = true;
break;
case 2:
// code
checkValue = true;
break;
case 3:
// code
checkValue = true;
break;
default: // when entered a wrong number
System.err.println("Wrong Input");
checkValue = false;
}
}
catch(Exception e) { // when entered a character
System.err.println("Wrong Input");
checkValue = false;
}
System.out.println("Program Ends");
This will work
catch (Exception e) { // when entered a character
System.err.println("Wrong Input");
checkValue = false;
console = new Scanner(System.in);//Edit
}
boolean checkValue = true;
Scanner console = new Scanner(System.in);
while (checkValue) {
System.out.println("Enter 1, 2 or 3");
try {
input = console.nextInt();
switch (input) {
case 1:
// code
checkValue = false;
break;
case 2:
// code
checkValue = false;
break;
case 3:
// code
checkValue = false;
break;
default: // when entered a wrong number
System.err.println("Wrong Input");
checkValue = false;
}
}
catch(Exception e) { // when entered a character
System.err.println("Wrong Input");
checkValue = false;
}
}
Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}