• Post Reply Bookmark Topic Watch Topic
  • New Topic

Infinite loop?? keyboard.nextInt() doesnt collect new data...  RSS feed

 
João Carapinha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I'm trying to collect an integer value from the keyboard and insist while diferent types of values are given.

Because when for example a char value is given, an InputMismatchException is thrown,
I wrote a try-cactch block inside the while loop, but after reading from the keyboard the first time
it begins an infinite loop without never asking for the key again.
I don't understand why this happens. i'm fairly new to java, maybe its a simple thing I'm not getting,
but I would very much appreciate your help on this subject as soon as possible.

This is it (short version ):

Scanner kb = new Scanner(System.In);
int key = 0;
boolean flag = true;
while (flag) {
try {
key = kb.nextInt();
flag = false;
} catch (InputMismatchException e) {
System.out.println("Invalid number. Try Again:");
}
}

thanks in advance,
PsYcK1K.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would do a check here:

key = kb.nextInt();
flag = false;

Instead of this code why don't you do a print statement to see what value "key" is before changing your flag?
 
João Carapinha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well,

I could try that, yes, but the problem persists 'cos when the exception occurs (inserting a char value, for example)
in the try block, the order of processing goes directly to the catch. The key variable never gets changed cos the
exception was thrown. Only if the value inserted is an integer the flag will be changed.

The problem here, as I checked in the debug of eclipse, is that in the 2nd loop the method nextInt() doesnt stop the execution
and ask for a new value, it's as if it wasnt there, and the loop goes on infinitively... it only reads the nextInt() the first
time and I dont understand why.

any ideas ??? :S

please
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when you run that loop? Do you get an exception? Does the value of flag change?

Have you searched whether anybody else had similar problems recently? Did you find this?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!