wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes try catch stuck in a loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "try catch stuck in a loop" Watch "try catch stuck in a loop" New topic
Author

try catch stuck in a loop

Daniel Clark jr
Greenhorn

Joined: Mar 01, 2009
Posts: 2
I'm trying to make a loop that checks to make sure a user inputs a number. but when I enter any none number it the catch gets stuck in a loop.
boolean notInt = true;
while(notInt)
{
try
{
//reads the amount of meters the user typed
meters = keyboard.nextInt();
notInt= false;
}
catch(InputMismatchException e)
{
meters = 0;
System.out.println("opps, you did not enter a valid option.");
}
}


I am really hoping some one could tell me what I missed.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18756
    
  40


Hint: After nextInt() chokes because it encounters the non-number. How do you get rid of the non-number?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
kannan vinayagam Duraiswamy
Ranch Hand

Joined: Jan 12, 2009
Posts: 52
please see the line 1,


import java.util.InputMismatchException;
import java.util.Scanner;
class AA
{
public static void main(String g[])
{
boolean notInt = true;
int meters=-1;
Scanner keyboard=new Scanner (System.in);
while(notInt)
{
try
{
//reads the amount of meters the user typed
meters = keyboard.nextInt();
notInt= false;
}
catch(InputMismatchException e)
{
meters = 0;
System.out.println("opps, you did not enter a valid option.");
notInt= false; // line 1
}
}
}
}


Kannan.DV
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38467
    
  23
You may be able to sort that out with the hasNextInt method of Scanner. Put that in the test part of your while loop, then you get the error message and "please try again" whenever a non-number is entered. You may need to get rid of the last input, as Henry has suggested; a look at the methods of Scanner will help.
Than you can dispense with the try-catch.

And please use the CODE button; your posts are difficult to read.
Daniel Clark jr
Greenhorn

Joined: Mar 01, 2009
Posts: 2
thank you very much, I'll try your advice. for now I put it in a string and casted the string in the try catch.
 
 
subject: try catch stuck in a loop