I want to understand how exception handling in Java works and I wrote simple method to set number (by typing it in console; using Scanner). Method doesn't work properly because it don't see numbers which are typed in try block and it always return -1;
Can somebody explain me is it possible to change number in my code using try block? As I've said i want to understand how exception works.
static int numberOfRows() {
int rows = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows");
while (!scan.hasNextInt()) {
try {
rows = scan.nextInt();
} catch (Exception e) {
System.out.println("Error - type another value");
scan.next();
}
scan.close();
}
return rows;
}
Thanks to your help I resolved my problem:
static int numberOfRows() {
int rows = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows");
while (!scan.hasNextInt()) {
try {
rows = scan.nextInt();
} catch (Exception e) {
System.out.println("Error - type another value");
scan.next();
continue;
}
}
rows = scan.nextInt();
scan.close(); // closing scanner may cause problems with InputStream //Link [1]
return rows;