Search code examples
javaiojava.util.scannerbufferedreader

How to tell BufferedReader to stop reading from System.in?


I am using bufferedReader to read System.in from the user, The user will enter a domain address and source address separated by a space.

eg 
auckland.ac.nz. 198.19.20.44
www.esc.auckland.ac. 173.27.28.93
stat.auckland.ac.nz. 52.159.152.105
student.auckland.ac.nz. 64.247.240.232

Now the problem is that once the user finishes entering the data, the input stream does not terminate and hence the program does not get executed. I have written some code for the BufferedReader if anyone is willing to check it and tell me where I went wrong I would greatly appreciate it. Notice the two variables "count" and "n", is there anyway I can use those to help with that?

     try {
        String fqdn, src, key, temp;
        Integer count;
        int n = 0;

        while ((temp = br.readLine()) != null){
            int divide = temp.indexOf(" ");
            fqdn = temp.substring(0, divide); // divide the input 
            src = temp.substring(divide+1);
            key = fqdn + " " + src;
            //System.out.printf("%d: %s\n", n, key);
            dht.lookup(key);
            n += 1;
        } 
        br.close();
    } catch (NoSuchElementException e) {
        //System.out.printf("end-of-file\n");    
    }

Solution

  • The loop will terminate when readLine() returns null. The only way that this will happen is if standard input it closed. The user can do this by typing Ctrl+D, but that's perhaps too much to ask from a typical user. One easy alternative is to ask them to type "done" when they're done; then your loop should check for that value, rather than null.