• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try catch stuck in a loop

 
Daniel Clark jr
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21518
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Henry
 
kannan vinayagam Duraiswamy
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
}
}
}
}
 
Campbell Ritchie
Sheriff
Pie
Posts: 50289
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic