Java how to stop scanner object skipping

w‮‬ww.lautturi.com
Java how to stop scanner object skipping

If your scanner object is skipping input, it may be because it is reading multiple lines at once or encountering a delimiter character in the input stream.

To stop the scanner from skipping input, you can use the following techniques:

  1. Use the nextLine method instead of the next method to read input. The nextLine method reads a line of input, whereas the next method reads only the next token (delimited by whitespace or a specified delimiter).

  2. Use the useDelimiter method to change the delimiter pattern used by the scanner. By default, the scanner uses a pattern that matches any sequence of one or more whitespace characters as the delimiter.

  3. Use the hasNext method to check if there is more input available before calling the next or nextLine method. This will allow you to read input only when it is available, rather than skipping input if it is not available.

Here's an example of how you can use these techniques to read input from the scanner:

Scanner scanner = new Scanner(System.in);

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    // Process the input line
}

scanner.close();

This code reads lines of input from the scanner until there is no more input available, and processes each line as it is read.

Note that the scanner object should be closed when you are done using it, to release any resources it is using. You can use the close method to close the scanner object.

Created Time:2017-11-03 23:27:12  Author:lautturi