I have been learning JAVA and i have a small doubt about the code :
class apple {
public static void main(String[] args) {
int[] num = new int[3];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num.length; i++) {
try {
num[i] = input.nextInt();
} catch (Exception e) {
System.out
.println("Invalid number..assigning default value 20");
num[i] = 20;
}
}
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
}
}
I have written small program to handle exception, if user input is not Int throw an exception and assign default value. If i put scanner statement inside for loop, it works fine, but if i take it outside its assign the same value at which exception was thrown i.e i am entering char rather than int. But if i enter all integers it assign correct values in array.
Scanner input = new Scanner(System.in);
I hope u guys have understood my question.
Scanner#nextInt
doesn't advance past the input if it fails to parse an integer, so if you keep calling it after failure, it will keep trying to parse same input again, throwing InputMismatchException
.
You can call Scanner#next
, ignoring the string it returns, in your catch
block to skip the invalid input:
try {
num[i] = input.nextInt();
} catch (Exception e) {
System.out
.println("Invalid number..assigning default value 20");
num[i] = 20;
input.next();
}
try
{
num[i] = input.nextInt();
}
catch(InputMismatchException ip)
{
System.out.println("Invalid number..assigning default value 20");
num[i] = 20;
input.next();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With