Netbeans - input.hasNext() does nothing upon hitting ctrl+z

Crais picture Crais · Jan 20, 2011 · Viewed 7.3k times · Source
while ( input.hasNext() ) {
            i = input.nextInt();
            //System.out.println();
            System.out.print("Bla: ");            
        }

this was just a test app/code. When I hit ctrl+z I just hear the ding Windows sound (aka you're doing it wrong sound <.<) and nothing happens, program continues running normally. I tested it in another app and input.hasNext() does return the correct True boolean value, it just won't recognize Ctrl+Z. Using Netbeans 6.9.1 and Windows 7.

Answer

Jim picture Jim · Jul 24, 2012

CTRL-Z indeed does end input in the console input stream for System.in on a Windows 7 platform.

It helps to understand the way this works. A large number of the Scanner methods, particularly the hasNext... and next... methods, block execution until something shows up in the System.in byte stream being processed by the Scanner object instanced. Once there is input of some kind, the methods will unblock and proceed as they are advertised.

The hasNext... methods will return boolean false if the input was end of input stream (i.e. CTRL-Z in Windows, CTRL-D in UNIX/Linux). If the hasNext... is specific to a primitive or other type, it will return a boolean true only if the input parses to a valid primitive or object type for which the hasNext... tests, otherwise it will return false.

In the case of hasNext(), it is not primitive or object specific, so any input other than an end of input stream will return true. This makes it very useful for the kind of determination this question implies.

The following code works on a Windows 7 Ultimate platform and, instead of nextInt() method, it uses a more general nextLine() method to demonstrate how this works. The nextInt() method restricts the user to integers and will throw an exception if something other than end of input or an integer that is not too big for the int primitive gets entered. This code will echo whatever the user types in until it gets an end of input character.

// ControlZEndInputTestApp.java
// Demonstrate how end of input
// works with Scanner.hasNext() method

import java.util.Scanner; 

public class ControlZEndInputTestApp {

    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        // hasNext() blocks until something appears in the System.in
        // byte stream being processed by Scanner or an end of stream
        // occurs which is CTRL-Z in Windows and CTRL-D in UNIX/Linux
        // When hasNext() unblocks, it returns boolean false
        // if the stream ended or boolean true if the input was anything else
        // other than an end of input stream
        // repeat as long as we don't receive an end of input
        // i.e. CTRL-Z on Windows or CTRL-D on UNIX/Linux...
        while ( input.hasNext() ) { 
              System.out.println(input.nextLine());
        }
    }
}