• Post Reply Bookmark Topic Watch Topic
  • New Topic

Maybe I miss something  RSS feed

 
Avi Freege
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my code:

while (LegalSlot == 0) {
if (gslots[anser].getplaya() > 0) {
gslots[anser].removplayer(1);
if (gslots[anser+numcube].getladderRope() == 0) {
gslots[anser+numcube].addplayer(1);
} else {
gslots[gslots[anser+numcube].getladderRope()].addplayer(1);

}
flag++;
LegalSlot = 1;
} else {
System.out.println("Ilegal Slot Pick Again;");
try {
anser = (input.nextInt())-1;
} catch (InputMismatchException e) {

}

}
Now I want to catch the exception if the user enters char such has 'a' 'b' and anything other than int , but when he catches the exception I want him to come back to the line : anser = (input.nextInt())-1;
to recieve new input from the user but somehow he just keep going threw the code. So my question is how do I make him come back to the the input line I mentioned?
thanks.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Avi Freege
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried that for some reason he is going back to the start of the loop and completely ignores the raw:

try {
anser = (input.nextInt()) - 1;
} catch (InputMismatchException e) {
System.out.println("Please Try Again");

thats gets an input from the user and I get the loop keep going and going
I debuged it and I dont understand why when he reaches the raw
anser = (input.nextInt()) - 1;
he is not stopping and waiting for an input
hope someone can explain it to me.
but thanks.
 
Campbell Ritchie
Sheriff
Posts: 53774
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

Rob Spoor points out it is completely possible to avoid the InputMismatchException like this, or something rather similar:
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15862
81
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avi, welcome to JavaRanch.

Please use code tags when you post source code, so the forum can format it for you.
 
Rob Spoor
Sheriff
Posts: 20895
81
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Welcome to JavaRanch

Rob Spoor points out it is completely possible to avoid the InputMismatchException like this, or something rather similar:

Correct. The input.next() inside the method is used to consume the non-int. The guard is slightly wrong though; it should also check for input.hasNext:
I think I forgot the hasNext() before in the loop, but that could cause an exception with the input.next() call if the stream is closed.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!