1

So this is my code for a crash proof scanner class:

import java.util.*;
public class BPScanner {
    Scanner kb = new Scanner(System.in);
    public int nextInt() {
        while (true) {
            try {
                String input = kb.nextLine();
                int i = Integer.parseInt(input);
                return i;
        }
            catch (NumberFormatException e1) {}
            catch (NoSuchElementException e2) {}
            System.out.print("\nPlease input an integer: ");
            kb.close();
            kb = new Scanner(System.in);
        }
    }    
}

I am calling this class from another class:

public void scnr() {
    while (true){
        System.out.print("Type a num (for test), (0 to break)");
        int n = bpkb.nextInt();
        if (n == 0) break;
        System.out.println(n);
    }
}

When I run it it returns an infinite loop that keep saying:

Please input an integer: 
Please input an integer: 
Please input an integer: 
Please input an integer: 

Any ideas how to fix it? Thank you very much in advance.

Charles
  • 50,943
  • 13
  • 104
  • 142
Le Dude
  • 47
  • 1
  • 5
  • 2
    In nextInt() you have infinite while with out break, I don't know why you have that there. – kosa Dec 08 '12 at 02:52
  • Just take out `while(true)` in `nextInt()` and it'll work :) – irrelephant Dec 08 '12 at 02:53
  • @Nambari and @irrelephant thank you for your reply. However I added a break but it still doesn`t work.. (the reason I use while(true) is that I want user to keep input and int until it works) – Le Dude Dec 08 '12 at 03:14
  • @WangZhongtian I think you do not get the concept of a `Scanner`. A `Scanner` automatically blocks other operations while waiting for user input. You do not need an infinite loop to keep checking if more input is available. – Extreme Coders Dec 08 '12 at 03:19

1 Answers1

1

Just remove the following codes from nextInt function:

kb.close();
kb = new Scanner(System.in);
bhuang3
  • 3,493
  • 2
  • 17
  • 17
  • 1
    To elaborate on that: when you close the scanner, you also close System.in. From then onwards, every time the new kb tries to read from System.in it will generate an exception: No line found. You should never ignore exceptions with {}, in this case you would have seen what was going wrong if you had at least printed out the exception. – Diego Basch Dec 08 '12 at 03:06
  • I added a break but it still doesn`t work.. (the reason I use while(true) is that I want user to keep input and int until it works) – Le Dude Dec 08 '12 at 03:12
  • @Wang Zhongtian Where do you add break? The reason why you enter an infinite loop is that when you're failed to parse the integer from a string, you close your `Scanner`, and when it tries to read `nextLine`, it throws `NoSuchElementException` – bhuang3 Dec 08 '12 at 03:18