Catch isn't catching InputMismatchException? - java

So, I've searched around google and stackoverflow for a bit, but I can't seem to find an answer to this issue.
I've got 2 methods. The first method, getAge is meant to just get an integer as input from the user. It's then meant to pass that input to verifyAge, who makes sure it's in the right range.
However; if they should enter anything that is not an integer, it's supposed to display a message and call getAge again, to restart the input process. I have a try-catch set up, but it still goes back to JVM. According to an answer in another post; what I'm doing is correct. But it still doesn't seem to be working. So here's the errors I get when I try to run it as I have it now:
Please enter your age: notint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Ch2ProgLabWilson.getAge(Ch2ProgLabWilson.java:22)
at Ch2ProgLabWilson.main(Ch2ProgLabWilson.java:15)
What I have written:
import java.util.* ;
import java.util.Scanner;
public class Ch2ProgLabWilson {
public static void main(String[] args) {
getAge();
}
public static int getAge()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
getAge();
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}
return a;
}
//
public static boolean verifyAge (int a)
{
if (a >= 0 && a <= 122)
{
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}
else
{
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
getAge();
return false;
}
}
}

The Exception is being thrown by int a = keyboard.nextInt();, which is outside of the try catch block.
Place the call to int a = keyboard.nextInt(); inside the try block.
There are other problems with your code:
verifyAge() returns a boolean that is never used.
Your getAge() method is recursive and, assuming that the user enters a number, it will just loop - is this what you intended?
UPDATE
public static int getAge(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = -1;
while(!verifyAge(age)){ // will loop until there's a valid age
try{
age = scanner.nextInt();
catch (InputMismatchException e){
System.out.println("You may only enter integers as an age. Try again.");
}
}
return age; // your current code doesn't do anything with this return value
}
public static boolean verifyAge (int a){ // would be better named isValidAge()
if (a >= 0 && a <= 122){
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}else{ // no need to call getAge() here
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
return false;
}
}

well the code is not within the try block
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
so it will not get caught.

Look at the line of code which actually throws the Exception. If it is not in the try/catch block, it will not be caught.
Try this instead:
try
{
int a = keyboard.nextInt();
verifyAge(a);
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}

Related

how do i implement user input in loop in the following code?

this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements

What to do if InputMismatchException keep looping?

I'm trying to create simple Menu for my program. I use InputMismatchException to catch exception when user enter char instead of integer but the program is looping when I enter char.
I left callMenu method empty but I'll fill it after solving this problem.
I am not sure is the mistake in the main menu or in catch part. When I do not write kb.nextInt() in catch section I'm getting infinitive loop. In another case it displayes mistake
public static void main(String[] args) {
do {
Menu.showMenu();
Menu.callMenu(Menu.getChoice());
} while (true);
}
}
import java.util.Scanner;
import java.util.Scanner.*;
import java.util.InputMismatchException;
public class Menu {
public static void showMenu() {
System.out.println("----------Menu----------");
System.out.println("1 - ");
System.out.println("2 - ");
System.out.println("0 - Exit");
}
public static int getChoice() {
Scanner kb = new Scanner(System.in);
System.out.print("\n Enter menu number:");
int choice = kb.nextInt();
while (!isValidChoice(choice)) {
try {
System.out.println("\n INVALID INPUT. Try again.");
System.out.print("Enter menu number: ");
choice = kb.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error");
kb.next();
}
}
return choice;
}
public static boolean isValidChoice(int ch) {
return ch >= 0 && ch <= 9;
}
public static void callMenu(int menuNum) {
switch (menuNum) {
case 1:
break;
case 2:
break;
case 0:
System.exit(0);
}
}
}
I am not going to modify your code a lot. Here is what i can see wrong and what i think you can change
The point that your are getting the first input will throw an exception if you do not enter a integer. You do not have a catch block around it. So you should take that inside the try catch block to capture any invalid inputs
The main method will keep running infinitely when you check the value as "true" in while condition. Change that to false.
What i am providing you below assumes that your program will exit if an character/Non-Integer value in entered by displaying an error message.If the inputs are integers, your code will loop until one of your correct menu items are reached
I am only putting in the changes and not the whole code below. Rest remains same.
public static int getChoice() {
Scanner kb = new Scanner(System.in);
System.out.print("\n Enter menu number:");
int choice=-1;
try{
choice = kb.nextInt();
while (!isValidChoice(choice)) {
System.out.println("\n INVALID INPUT. Try again.");
System.out.print("Enter menu number: ");
choice = kb.nextInt();
}
}catch (InputMismatchException e) {
System.out.println("Error");
}
return choice;
}
In your main method
public static void main(String[] args) {
do {
Menu.showMenu();
Menu.callMenu(Menu.getChoice());
} while (false);
}
Hope this works out. Let me know

Ask to insert numbers only

So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}

How is nextLine() discarding input in this code?

If I remove input.nextLine() from the catch block, an infinite loop starts. The coment says that input.nextLine() is discarding input. How exactly is it doing this?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
One more thing.. The code listed below, on the other hand, works perfectly without including any input.nextLine() statement. Why?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
System.out.println(x[i]);
}
}
Because input.nextInt(); will only consume an int, there is still pending characters in the buffer (that are not an int) in the catch block. If you don't read them with nextLine() then you enter an infinite loop as it checks for an int, doesn't find one, throws an Exception and then checks for an int.
You could do
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required) " +
input.nextLine() + " is not an int");
}

how to check whether the input is integer or not

I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.
Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}
here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!
Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.
public void checkInt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
try {
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.print("this is even!!");
} else {
System.out.println("this is odd!!");
}
} catch (InputMismatchException e) {
System.out.println("pleas enter an integer only!!!");
checkInt();
}
}
You must read user input as String. Then, inside a try/catch block, make a casting to integer (Integer.parseInt()), if throws a exception is because is not a number.
May be a stupid way but this can solve your problem:
String x;
x = "5";//or get it from user
int y;
try{
y = Integer.parseInt(x);
System.out.println("INTEGER");
}catch(NumberFormatException ex){
System.out.println("NOT INTEGER");
}
Edited:
The program will try to convert the string to integer. If it is integer it will succeed else it will get exception and be caught.
Another way is to check the ASCII value.
To continue till integer is encountered:
String x;
Scanner sc = new Scanner(System.in);
boolean notOk;
do{
x = sc.next();
notOk = check(x);
}while(notOk);
System.out.println("Integer found");
}
private static boolean check(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}
import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("Input is of int type");
else
System.out.println("This is something else");
}
}

Categories