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 :).
Related
I am very new to java and I am trying out error handling. I am pretty proficent in python and I know the error handling in python would go
while True:
try:
*some code*
except IndexError:
continue
break
I would like to know what the equivalent of a retry loop after exception is in java
EDIT:
This is what I have so far, however whenever a exception is thrown it does an infinite loop saying "Enter an Short: Error Try again."
while(true)
{
try {
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
break;
}
catch (InputMismatchException e) {
System.out.println("Error Try again.");
continue;
}
}
To clarify what exactly I would like is. When "InputMismatchException" is thrown the loop re runs and prompts the user again and it does this until the user gives the correct input. I hope that clarifies what I would like it to do.
What you have is almost good as #Thomas mentioned. Just need to add some brackets and semicolons. It should look line following code.
while(true){
try{
// some code
break; // Prevent infinite loop, success should break from the loop
} catch(Exception e) { // This would catch all exception, you can narrow it down ArrayIndexOutOfBoundsException
continue;
}
}
As your question asks about error handling and you showed IndexError as an example, the equivalent in Java could be:
try {
//*some code*
}
catch(ArrayIndexOutOfBoundsException exception) {
//handleYourExceptionHere(exception);
}
About ArrayIndexOutOfBoundsException, you take a look here, in the documentation. About Exceptions, in general, you can read here.
EDIT, according to your question edition, adding more information...
while(true)
{
try {
System.out.print("Enter a short: ");
short myShort = reader.nextShort();
System.out.println(myShort);
}
catch (InputMismatchException e) {
System.out.println("Error! Try again.");
//Handle the exception here...
break;
}
}
In this case, when the InputMismatchException occurs, the error message is exhibited and the break should leave the loop. I do not know yet if I understand well what you are asking, but I hope this helps.
To the help of #Slaw he determined that scanner would keep inputting the same value unless I closed it at the end of the loop and here is the working code.
while (true)
{
Scanner reader = new Scanner(System.in);
try
{
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
reader.close();
break;
}
catch (InputMismatchException e)
{
System.out.println("Error Try again.");
}
}
I recently asked if there is any possible way whatsoever to get an exception from assigning a value to a String variable with the Scanner (The thread is here:)
And one of the guys told me that CTRL+D would be a case where a NoSuchElementException could be thrown. This to me is kind of a special case because input.nextLine() returns a String, and a String can be basically anything a user could type on the keyboard, so one would assume that input.nextLine() would not be a concern to throw an exception.
So I decided to add some try catch blocks into a program I'm writing on the off chance that CTRL+D is pressed when the program is asking for a number.
The problem I've run into is that when I catch the CTRL+D exception, the Scanner needs to be flushed, but if I flush the Scanner, it will cause a NoSuchElementException to occur because no new line exists. I'm using this all in a while true loop, so I'm kind of stuck between a rock and a hard place.
I will post one version of the code, with the input.nextLine() commented out. If you run it as is, you will get the infinite loop that happens when the Scanner needs to be flushed. If you uncomment the input.nextLine(), that very line of code will itself cause a NoSuchElementException.
import java.util.NoSuchElementException;
private int getMainOptions(){
System.out.printf("\n********** Main Options **********");
System.out.printf("\n*%32s*", "");
System.out.printf("\n* %-30s*", "[1] Create Customer");
System.out.printf("\n* %-30s*", "[2] Create Reservation");
System.out.printf("\n* %-30s*", "[3] Display Customer");
System.out.printf("\n* %-30s*", "[4] Display Reservation");
System.out.printf("\n*%32s*", "");
System.out.printf("\n**********************************");
while(true){
try{
System.out.print("\nChoose Option: ");
if(input.hasNextInt()){
return input.nextInt();
}
System.out.print("\nInvalid option");
input.nextLine();
continue;
}
catch(NoSuchElementException e){
System.out.print("\nAn exception occurred.");
//input.nextLine();
}
}
}
Apart from creating the Scanner inside the while loop and destoying it in the catch to be recreated in the next iteration, what can be done to solve this problem?
The code goes into an infinite loop when the input.nextLine() is commented out or when input.hasNextLine() is there to check because it is in a while(true) loop with nothing to stop it since input.nextInt() is not called. if(input.hasNextInt()) will not wait for an int, but simply skip the code inside the if statement if an int is not present as input.
Instead try this:
while(true){
try{
System.out.print("\nChoose Option: ");
String in=input.nextLine();
try{
int i=Integer.parseInt(in);
return i;
}catch(NumberFormatException ex)
{
System.out.print("\nInvalid option");
}
}
catch(NoSuchElementException e){
System.out.print("\nAn exception occurred.");
//input.nextLine();
}
}
}
I hope this helps and that I am understanding the question correctly
I'm not sure you fully grasp what happens when the user presses Ctrl-D. When that happens the standard input stream is closed. There is no way to reopen a closed stream. Even if you create a new Scanner and pass it in System.in it will still throw a NoSuchElementException.
As a Linux user if I press Ctrl-D in an interactive program, I expect the program to terminate. That is really all you can do at that point.
I'm trying to read a number for a switch case option but I'm stuck with an exception. I will try to explain the problem better in code:
do{
try{
loop=false;
int op=teclado.nextInt();
//I tryed a teclado.nextLine() here cause i saw in other Q but didn't work
}
catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
loop=true;//At the catch bolck i change the loop value
}
}while(loop);//When loop is true it instantly go to the catch part over and over again and never ask for an int again
When I type an int it works perfectly, but the exception makes it start over. The second time, the program does not ask for the int (I think it could be a buffer and I need something like fflush(stdin) in C), and the buffer just starts writing like crazy.
You would be well-served creating a new instance of Scanner from within the catch to get the input should you fail. EDIT: You can use a Scanner.nextLine() to advance past the newline character when you fail. A do...while loop may be inappropriate for this, since it guarantees that it will execute at least once.
A construct that may help you out more is a simple while loop. This is actually a while-true-break type of loop, which breaks on valid input.
while(true) {
try {
op=teclado.nextInt();
break;
} catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
teclado.nextLine();
}
}
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.
And yes, I am new to Java
nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().
Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.
Try using
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
try{
//let user know you are now asking for a number, don't just leave empty console
System.out.println("Please enter a number: ");
String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
//test if user entered a number in that line
int number=Integer.parseInt(lineEntered);
System.out.println("You entered a number: "+number);
isInValidResponse = false;
}
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
catch (Exception e){
System.out.println("I did not understand what you said. Try again: ");
}
}
Because of common topic of avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/
I'm writing a straight forward Airport Terminal style program for class. I'm going beyond the scope of the assignment and "attempting" to use Try/Catch blocks...
However Java is being that guy right now.
The problem is that when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
Why?
Edit - Also the containsOnlyLetters method works, unless someone thinks that could be the error?
System.out.println("\nGood News! That seat is available");
try
{//try
System.out.print("Enter your first name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
firstName = temp;
else
throw new Exception("First name must contain"
+ " only letters");
System.out.print("Enter your last name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
lastName = temp;
else
throw new Exception("Last name must contain"
+ " only letters");
}//end try
catch(Exception e)
{//catch
System.out.println(e.getMessage());
System.out.println("\nPlease try again... ");
}//end catch
passengers[clients] = new clientInfo
(firstName, lastName, clients, request, i);
bookSeat(i);
done = true;
You seem to misunderstand the purpose and mechanism of try/catch.
It's not intended for general flow control, and more specifically, the meaning is not that the try block is repeated until it finishes without an exception. Instead, the block is run only once, the point is that the catch block will only execute if a matching exception is thrown.
You should use a while loop and if clauses for your code, not try/catch.
If a Throwable or Error is generated it won't be caught by your handler. You could try catching Throwable instead.
What do you mean when you say
when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
It is not clear the outcome you expect, are u thinking that once the exception is caught, control will go back into the try block? That is not how it is intended to work.
When an exception is thrown, the control goes to the appropriate catch/finally blocks and then moves ahead, remaining lines in the try block are not executed