Scanner inputMismatch - java

This is my code (simplified).
public class A {
int num;
public void method () {
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
switch (num) {
case 1:
System.out.println("Hello 1");
scanner.close();
break;
case 2:
System.out.println("Hello 2");
scanner.close();
break;
case 3:
System.out.println("Hello 3");
scanner.close();
break;
default:
System.out.println("\nPlease try again.");
method();
}
}
}
I want any non-integer input like Strings to also run the default case and sysout the "Please try again" instead of getting an inputMismatch error, but i have no idea how to do it.
Basically any input that is not a 1,2 or 3 should jump to the default case.

You can't do this through this code as you are taking user input as integer and if you will enter a string it will through inputMismatch error as the compiler is expecting integer but getting string or character input.
Now what you can do is take a string as the user input. Here the complete code for you:
public class A {
String num;
public void method () {
Scanner scanner = new Scanner(System.in);
num = scanner.nextLine();
switch (num) {
case "1":
System.out.println("Hello 1");
scanner.close();
break;
case "2":
System.out.println("Hello 2");
scanner.close();
break;
case "3":
System.out.println("Hello 3");
scanner.close();
break;
default:
System.out.println("\nPlease try again.");
method();
}
}
}
This is what you want. It will work for every input.

Use scanner.hasNextInt() to check if the input is an integer. If not, assign zero to num which then results in matching the default.

You can't get strings by num = scanner.nextInt();. But, I have an idea.
value = scanner.nextLine();
//Now, check it is string or int
boolean numeric = true;
try {
Double num = Double.parseDouble(value);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric){
Integer.parseInt(value)
}else{
//you can write value= value. Or, you can left it empty also. Or, you can remove else statement also.
}
switch (num) {
case 1:
System.out.println("Hello 1");
scanner.close();
break;
case 2:
System.out.println("Hello 2");
scanner.close();
break;
case 3:
System.out.println("Hello 3");
scanner.close();
break;
case "Hello":
System.out.println("Hello 3");
scanner.close();
break;
default:
System.out.println("\nPlease try again.");
method();
}
#Badal is correct also. And, I did it with keeping int value. And, I don't remember is there any other way to check is it string or not. So, Sorry.

Related

Stuck in Infinite loop, why it does not wait for scanner to re-enter the values [duplicate]

my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.

Scanner + switch use

I'm a new to Java.
I'm currently doing a side project; making a text based game. and I realized that using Switch-statement would be very useful for this type of game.
So it is basically how it works.
I ask User, what would you like to do?
Eat
Walk
etc.
So, what would be the best way to build a switch-statement and Scanner together along with "default statement that asks User again"?
I've been doing this way(my code down here), but it seems it has so many potential problems.
Could you guys give me some hints on how to make a best switch-statement with Scanner?
Thank you very much in advance.
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (!sc.hasNextInt()) {
sc.next();
}
select = sc.nextInt();
switch (select) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); //would you re call itself again here? or is there any otherway to do without recalling itself?
}
Your code seems ok but I would refactor it. Also add while loop to ask again:
public static void ask() {
Scanner sc = new Scanner(System.in);
boolean isWrongAnswer;
do {
isWrongAnswer = false;
System.out.println("What do you want to do?");
switch (sc.nextInt()) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
isWrongAnswer = true;
}
} while (isWrongAnswer);
}
It is good to check first that scanner has something or not then check for whether it is int value. To do that can use sc.hasNext() & sc.hasNextInt() like below,
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (sc.hasNext()) {
int select = 0;
if (sc.hasNextInt()) {
select = sc.nextInt();
}
switch (select) {
case 1:
System.out.println("call eat()");
break;
case 2:
System.out.println("call walk()");
break;
case 3:
System.out.println("call sleep()");
break;
default:
System.out.println("choose from 1 to 3");
ask();
}
}
I advise you to use String in this case. To improve the readability of the code, and to avoid errors.(http://www.oracle.com/technetwork/java/codeconventions-150003.pdf)
private static final String EAT = "1";
private static final String WALK = "2";
private static final String SLEEP = "3";
public void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
switch (sc.next()) {
case EAT:
eat();
break;
case WALK:
walk();
break;
case SLEEP:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); // as described above via "do while", but there is nothing wrong with recursion. The garbage collector works.
}
}

Want to create a condition that checks were the input is a integer ranging from 1 to 5

I Want to create a condition that checks were the input is a integer ranging from 1 to 5.
but it keeps saying input matching exception, can you guys help?
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(">> You have selected ["+choice+"]");
//loops until input is an integer ranging from 1 to 5
while(!scan.hasNextInt() && choice>0 && choice<6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
break;
}
}
}
Try this:
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
//input variable
String in;
//loops until input is an integer ranging from 1 to 5
while (scan.hasNextLine()) { //checks if there is a new line of input
in = scan.nextLine().trim(); //scans that line
if (!in.matches("^[1-5]$")) { //tests if input is a single positive digit 1-5
System.out.println(">> You put wrong input");
continue;
}
int choice = Integer.parseInt(in);
System.out.println(">> You have selected ["+choice+"]");
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
}
}
}
}
I have slightly altered your code to not only keep persisting the user for a valid input, but also correctly parse that input to avoid any errors. I also removed the default part of the switch block, only because the input validation prior eliminates the need for it.
I have not tested this code, but it should work properly :)
You are currently not updating the choice variable for each iteration, but rather only using the initial value. Furthermore, you're iterating until scan DOES NOT have an int, i.e. !scan.hasNextInt() and I guess you're intention is actually the opposite.
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice;
//loops until input is an integer ranging from 1 to 5
while(scan.hasNextInt() && (choice = scan.nextInt()) > 0 && choice < 6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
}
}
}
Hope it helps!

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.

Exception handling infinite loop

my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied, pasted and modified the appropriate variables from a previous program that worked. Below is the statement itself and below that will be the entire program. Thank you for your help!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
Program:
public class Blanco {
public static int input;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* #param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.

Categories

Resources