This question already has an answer here:
boolean z = false;
do {
try {
a = sc.nextInt();
z = true;
}
catch(Exception e) {
}
}
while(!z);
Try this. If you try an integer the first time it executes properly. However if you enter the wrong type of text it turns into an infinite loop even if you enter an int next and skips assigning the boolean value to true. Why is this?
Your problem is from not handling the end of line token and so the scanner is left hanging. You want to do something like so:
Also, while (z == false) is bad form. You're much better off with while (!z). This prevents the while (z = false) error, and is a cleaner way of expressing this.
edit for Marcelo:
Marcelo, thanks for your input and advice! Are you saying that the conditional in the if block below will not change the value of the boolean, spam?
Because if it does change it, the coder wouldn't expect this if they intended to write if (spam == false), then there could be subtle and dangerous side effects from this. Again, thanks for helping to clarify this for me!