1

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;
project50k
  • 19
  • 3
  • 1
    "Can somebody explain me is it possible to change number in my code using try block" Yes. Just like that. But you don't want to call `scan.close()` in the loop. – Andy Turner Feb 05 '18 at 22:18
  • 1
    The `try` block is fine; but your loop is a bit odd. You're saying "while I you don't have a foo, give me a foo". What do you expect to happen here? – Andy Turner Feb 05 '18 at 22:21
  • 1
    You should probably change your while loop condition. You want to loop while there is a next int present, not the opposite. So change it to 'while(scan.hasNextInt())' – TM00 Feb 05 '18 at 22:21

0 Answers0