I'm a beginner with Java and was attempting to catch the exception 'InputMismatchException'. Below is my code, I hope it is easy to read, apologies in advance if it's not formatted well. It builds fine and executes, but if I input a character for example the 'catch' doesn't function and the error comes up;
"Exception in thread "main" java.util.InputMismatchException"
I believe everything else in the code works fine including the 'try', and I don't have anything going in the catch other than a System.out.print command.
import java.util.*; // imports
public class w4q1
{
public static void main(String[] args)
{
Scanner user_input = new Scanner( System.in ); // declaring Scanner util
System.out.print("Please enter an integer: \n"); // Asks for input
int d = user_input.nextInt();
while (d > 0 || d < 0) // start of while loop, in the event of anything other than zero entered
{
try {
if (d < 0) // if statements
{
System.out.print("The integer " + d + " is negative\n");
break;
}
else if (d > 0)
{
System.out.print("The integer " + d + " is positive\n");
break;
}
else
{
System.out.print("You have not entered an integer\n");
break;
}
}
catch (InputMismatchException e) // Error message for letters/characters and decimals
{
System.out.print("You have entered an incorrect value, please restart the program\n");
}
}
if (d == 0)
{
System.out.print("A zero has been entered\n");
}
}
}
If you are still receiving an InputMismatchException even though you have a try-catch block, then the exception must be coming from somewhere outside of your try-catch block.
Look at what else outside the try-catch block can throw an InputMismatchException and put a try-catch block around that statement, or expand your existing try-catch block to include that statement.
If indeed the exception is not getting caught, then the resulting stack trace should show you the actual line of code which threw the exception. Looking at the code, I'm going to guess that this is where the exception occurs:
user_input.nextInt();
I would recommend you look at the stack trace and see if you can confirm this.
Put a try-catch block around this code
int d = user_input.nextInt();
and by so doing ,you also need to change the current code a little bit to make it OK. Good Luck !
Related
I am trying to program a method that handles user Input. The method needs to scan from the console an int, check if scanned int was in Range and then check the validity of the data before scanning another int in another method. I decided to program the method recursively, that it will call itself to repeat if the mentioned conditions are not met.
public static void readUserInputDay(Scanner scanner) {
System.out.print("Day (1-31): ");
try {
int tmp = scanner.nextInt();
day = new Integer(tmp);
if(isTheInputInRange(day.intValue(), DAY)) {
readUserInputMonth(scanner);
} else {
System.out.print("Number isn't in Range (1-31)\n");
readUserInputDay(scanner);
}
} catch (Exception e) {
System.out.print("Please enter a number!\n");
readUserInputDay(scanner);
}
}
The other filters work as expected, however if I enter on the console something that is not an int the Exception is triggered and catched (As expected) but when I expect the Method to recursively repeat itself, I instead get the following output on the console:
Day (1-31): Please enter a number!
Day (1-31): Please enter a number!
Day (1-31): Please enter a number!
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
at sun.nio.cs.UTF_8.access$200(UTF_8.java:57)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:636)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.PrintStream.write(PrintStream.java:526)
at java.io.PrintStream.print(PrintStream.java:669)
at MyClass.readUserInputDay(MyClass.java:27)
at MyClass.readUserInputDay(MyClass.java:43)
at MyClass.readUserInputDay(MyClass.java:43)
Do have any ideas how I need to fix the code, so when method call itself, it doesn't enter immediately in the catch block ?
Thanks in advance
you are calling the method inside of itself 3 times and according to conditions it cause to re-call it self and at the end overflow error.
to prevent from this problem at first try to change the structure of your code and use while loops for example to continue your code at a certain condition you want and get the result:
public static void readUserInputDay(Scanner scanner) {
try {
boolean isFinished = false;
// your condition for loop
while (!isFinished) {
System.out.print("Day (1-31): ");
int tmp = scanner.nextInt();
day = new Integer(tmp);
if (isTheInputInRange(day.intValue(), DAY)) {
readUserInputMonth(scanner);
isFinished = true;
} else {
System.out.print("Number isn't in Range (1-31)\n");
}
}
} catch (Exception e) {
System.out.print("Please enter a number!\n");
readUserInputDay(scanner);
}
}
It is odd that you say the StackOverflow error occurs on the first retry, especially within the first System.out.print call.
However, as Mustafa suggested, using a while loop rather than recursion is a much better choice in this case, as it will not cause new stack frames to be created every time somebody enters the wrong text (as I do not think that Java can do tail call optimisation on that method).
public static void readUserInputDay(Scanner scanner) {
while (true) {
System.out.print("Day (1-31): ");
try {
int tmp = scanner.nextInt();
day = new Integer(tmp);
if (isTheInputInRange(day.intValue(), DAY)) {
readUserInputMonth(scanner);
break; // exit the retry loop
} else {
System.out.print("Number isn't in Range (1-31)\n");
}
} catch (Exception e) {
System.out.print("Please enter a number!\n");
}
// By this point, the input is invalid, so loop again
}
}
I am making simple calculator program that initially and simply asks for a number in regards to addition, subtraction and division.
If they enter a number that is not 1,2 or 3 I want to create an IOException and then recall the method to allow the user to be asked the same question again.
Maybe I'm missing something obvious. Any help appreciated. Thank you.
((Assume that scanner and all other functions are working))
public static void mathsChoice() throws IOException{
System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division");
int resChoice = scanner.nextInt();
if (resChoice == 1){
additionMethod();
}else if (resChoice == 2){
subtractionMethod();
} else if (resChoice == 3){
divisionMethod();
}else {
throw new IOException("Not valid, try again.");
mathsChoice();
}
}
The "mathsChoice();" within the else clause is causing the error:
"Unreachable code"
mathsChoice();
It is telling you that mathsChoice() has no chance of execution ever. As in that particular block you are always throwing an exception which will terminate the program execution and the program will never reach this line mathsChoice()
You should put the mathsChoice() call after the else block is closed.
public static void mathsChoice() throws IOException{
System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division");
int resChoice = scanner.nextInt();
if (resChoice == 1){
additionMethod();
}else if (resChoice == 2){
subtractionMethod();
} else if (resChoice == 3){
divisionMethod();
}else {
throw new IOException("Not valid, try again.");
}
mathsChoice();
}
When you throw the IOException the method exits, and the mathsChoice(); line is never reached.
You may want to change it to a simple print out instead of an exception. System.out.println("Not valid, try again.");
I was tasked with creating an age program that when a user enters their name and age and the program checks to see the age is between 0 and 125. If not, the program shows an error code (use Exception Class).
My code:
import java.util.Scanner;
import java.io.IOException;
class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
super("The Age you've entered is not valid");
}
}
class age3
{
public static void main(String arg[])
{
try
{
int x, y;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("What is your name?");
String userInputName = userInputScanner.nextLine();
System.out.println("Nice to meet you " + userInputName +"!");
System.out.println("How old are you?");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = 125;
if (x<y)
System.out.println("Correct.Your age is less than 125");
else
System.out.println("Not Possible");
}
}
}
catch(InvalidAgeException e)
{
System.println("Invalid age error"+ e);
}
finally
{
System.out.println("Execution Completed")
}
Basically I made my statement that if false it should display a message saying they are wrong and also that at the end there should be an exception that shows simply that the person made an error.
These are my errors that I got:
3 errors
Mishas-MBP:desktop mishashtapov$ javac age3.java
age3.java:14: error: 'try' without 'catch', 'finally' or resource declarations
try
^
age3.java:32: error: class, interface, or enum expected
catch(InvalidAgeException e)
^
age3.java:35: error: class, interface, or enum expected
}
^
3 errors
So my question is how do I properly use the try, catch, finally methods so it displays the exception???
Any help would be appreciated. Thanks.
I used this outline that was on my online course:
Exception Handling
Creating a User-defined Exception
In Java, it’s possible to create your own exception rather than using the predefined exceptions. Creating your own exception is creating a user defined exception. Now look at the exception created based on age calculation.
You are asked to check the age of the user when they enter their age in a program. As you know, the age-range of a person is limited: say 0 (birth) to 125. In writing the program, you specify this range so that if a user gives a number which is outside this range, the program could show an error message to the user.
In this case, you have to create your own exception. Look at the steps in the code below that defines the creation of a new exception.
Class InvalidAgeException extends Exception
{
public InvalidAgeException()
{
super("The Age you've entered is not valid");
}
}
class TestException
{
public static void main(String arg[])
{
try
{
//Your Code Here
}
catch(InvalidAgeException ae)
{
System.println(“Your Exception”);
}
}
}
First, you need to fix the syntax errors.
catch and finally should follow the try block's closing curly brace. Also, it should be System.out.println rather than System.println. And, your exception should be created and thrown in your logic.
You code should be
try {
int x, y;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("What is your name?");
String userInputName = userInputScanner.nextLine();
System.out.println("Nice to meet you " + userInputName + "!");
System.out.println("How old are you?");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = 125;
if (x < y)
System.out.println("Correct.Your age is less than 125");
else {
throw new InvalidAgeException("Not Possible");
}
} catch (InvalidAgeException e) {
System.out.println("Invalid age error" + e);
} finally {
System.out.println("Execution Completed")
}
For how to use Exceptions. I think Oracle's document would be a good place to look at. See Exceptions.
You may try to throw your custom exception when your age check fails. That will cause the exception to be caught in catch clause and to print the error. Something like :
if (x<y)
System.out.println("Correct.Your age is less than 125");
else {
System.out.println("Not Possible");
//throw your exception here:
throw new InvalidAgeException();
}
First of all, you had some syntax errors.
try, catch and finally should follow each other. Also, it should be System.out.println instead of System.println in your catch.
Now the exception, you don't need a second class for your exception, just use Exception e, inbetween the brackets for the catch.
The following worked for me:
public class age3{
public static void main(String arg[]){
try{
int x, y;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("What is your name?");
String userInputName = userInputScanner.nextLine();
System.out.println("Nice to meet you " + userInputName +"!");
System.out.println("How old are you?");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = 125;
if (x<y)
System.out.println("Correct.Your age is less than 125");
else
System.out.println("Not Possible");
}catch(Exception e){
System.out.println("Invalid age error" + e);
}finally{
System.out.println("Execution Completed");
}
}
}
PS: try coding a bit neater next time, it is easier to read for both yourself and others :P
I am making a basic application where it trains your math skills. I have this code:
while (true)
{
try
{
int userAnswer;
System.out.println("Type quit to exit to the menu!");
int randInt = r.nextInt(num2);
System.out.println(num1 + " + " + randInt + " =");
userAnswer = in.nextInt();
if(userAnswer == num1 + randInt) System.out.println("Correct!");
else System.out.println("Wrong!");
break;
}
catch(Exception e)
{
}
}
When someone prints out a d or something in the answer, the try catch goes. But, then it goes to the while loop and repeatedly spams Type quit to exit to the menu and then something like 1 + 2 = infinitely... I think I know what's wrong, userAnswer has been assigned already as something that throws an exception that goes to the catch and it just keeps printing those and goes to the catch and goes back because userAnswer is already assigned. I think this is what is happening, I could be wrong. Please help!
EDIT: I forgot to make this clear, but I want the question to be re-printed again, exiting out of the loop goes to a menu where you can't get the question back, I want it to redo what's in the try catch...
You should never catch an Exception without handling it.
catch(Exception e)
{
System.out.println("An error has occured");
break;
}
This should stop your program from looping infinitely if an Exception occurs.
If user input comes as letter it will get an exception because you are trying to read(parse) as integer. So your catch clause is in the loop you have to write break in there to go out from loop.
Still i will suggest you to getline as string and than compare with your cli commands (quit in your case) than you can try to parse it as an integer and handle loop logic.
You're not breaking the while loop if there is a mismatch
while(true)
{
try
{
}
catch(InputMisMatchException e)//I suggest you to use the exact exception to avoid others being ignored
{
System.out.println("Thank you!");
break;//breaks the while loop
}
}
Yoy're not breaking the loop in case of Exception occurs.
Add break; statement in the catch block to run your program without going to infinite loop, in case exception occurs.
Since the given answers don't match your requirement I'll solve that "riddle" for you.
I guess what you didn't knew is that the scanner won't read the next token if it doesn't match the expectation. So, if you call in.nextInt() and the next token is not a number, then the scanner will throw an InputMismatchException and keeps the reader position where it is. So if you try it again (due to the loop), then it will throw this exception again. To avoid this you have to consume the erroneous token:
catch (Exception e) {
// exception handling
in.next();
}
This will consume the bad token, so in.nextInt() can accept a new token. Also there is no need to add break here.
Mind that in.next() reads only one token, which is delimited by a whitespace. So if the user enters a b c, then your code will throw three exception and therefore generate three different question befor the user can enter a number. You can avoid that by using in.nextLine() instead. But this can lead into another problem: Scanner issue when using nextLine after nextXXX, so pay attention to that :).
In the first try and catch it works exactly how I need it to however in the other two they don't and I am not sure why.
First One: It asks for a difficulty 1 - 3 if it isn't 1,2, or 3 it loops till they enter 1,2 or 3 and if they put anything but an int it will say "Invalid Difficulty" and ask for them to input again.
Issue: None (that I know of)
try {
System.out.println("What would you like the difficulty to be?");
System.out.println("Easy = 1, Medium = 2, Hard = 3");
difficulty = userInput.nextInt();
while((difficulty < 1 || difficulty > 3)){
System.out.println("Invalid Difficulty. \n");
difficulty = userInput.nextInt();
}
} catch(InputMismatchException exception) {
System.out.println("Invalid Difficulty.\n");
difficulty = selctDifficulty();
}
Second One: Should do the same as above just without the loop to male sure it falls between 2 numbers.
Issue: If they don't enter an int it says Invalid amount then crashes with
Exception in thread "main" java.util.InputMismatchException
try {
System.out.println("How many pitchers would you like to buy?");
amountOfPitchers = userInput.nextInt();
} catch(InputMismatchException exception) {
System.out.println("Invalid Amount.\n");
amountOfPitchers = userInput.nextInt();
}
Third One: Should work exactly as the first.
Issue: If I enter a string it crashes with
Exception in thread "main" java.util.InputMismatchException
try {
System.out.println("How much do you want to charge per cup?");
System.out.println("Between $0.05 and $2.00");
pricePerCup = userInput.nextDouble();
while((pricePerCup < 0.05 || pricePerCup > 2.00)){
System.out.println("Invalid Amount. \n");
pricePerCup = userInput.nextDouble();
}
} catch(InputMismatchException exception) {
System.out.println("Invalid Amount.\n");
pricePerCup = userInput.nextDouble();
}
Your error line tells you clearly what and where the error is:
Exception in thread "main" java.util.InputMismatchException
Something in your catch clause for your second and third example is giving you error, but not the first one. Do you see why?
Upon simple inspection, for your second and third try and catch, after an exception has occured due to invalid input, your are still attempting to process input using userInput.nextInt() and userInput.nextDouble(). The exception this causes will not be caught and is therefore causing problems.
You need to do userInput.next() in your catch in order to move to the next input
Your first appears to be recursive in the catch block, your third isn't...
System.out.println("Invalid Amount: " + userInput.next()); // <-- read the non-double.
// pricePerCup = userInput.nextDouble();
pricePerCup = selectPricePerCup();
Cause you do pricePerCup = userInput.nextDouble(); in catch?
If you catch it why you try to process input once again when it is not valid input?
Read about exceptions and what catch block really does.