- Class Scanner
- Java scanner.nextLine() Method Call Gets Skipped Error [SOLVED]
- Why Does the scanner.nextLine() Call Get Skipped After the scanner.nextInt() Call?
- How to Clear the Input Buffer After the scanner.nextInt() Call Takes Place
- How to Parse Inputs Taken Using the scanner.nextLine() Method
- Conclusion
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from the console.
As another example, this code allows long types to be assigned from entries in a file myNumbers :
Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong())
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
prints the following output:
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); MatchResult result = s.match(); for (int i=1; i
The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace() . The reset() method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The next() and hasNext() methods and their companion methods (such as nextInt() and hasNextInt() ) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext() and next() methods may block waiting for further input. Whether a hasNext() method blocks has no connection to whether or not its associated next() method will block. The tokens() method may also block waiting for input.
The findInLine() , findWithinHorizon() , skip() , and findAll() methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.
When a scanner throws an InputMismatchException , the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.
A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's read() method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
A Scanner is not safe for multithreaded use without external synchronization.
Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.
A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method. The reset() method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed.
Localized numbers
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault(Locale.Category.FORMAT) method; it may be changed via the useLocale() method. The reset() method will reset the value of the scanner's locale to the initial locale regardless of whether it was previously changed.
The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df , and its and DecimalFormatSymbols object, dfs .
LocalGroupSeparator The character used to separate thousands groups, i.e., dfs. getGroupingSeparator() LocalDecimalSeparator The character used for the decimal point, i.e., dfs. getDecimalSeparator() LocalPositivePrefix The string that appears before a positive number (may be empty), i.e., df. getPositivePrefix() LocalPositiveSuffix The string that appears after a positive number (may be empty), i.e., df. getPositiveSuffix() LocalNegativePrefix The string that appears before a negative number (may be empty), i.e., df. getNegativePrefix() LocalNegativeSuffix The string that appears after a negative number (may be empty), i.e., df. getNegativeSuffix() LocalNaN The string that represents not-a-number for floating-point values, i.e., dfs. getNaN() LocalInfinity The string that represents infinity for floating-point values, i.e., dfs. getInfinity()
Number syntax
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10). NonAsciiDigit: A non-ASCII character c for which Character.isDigit (c) returns true Non0Digit: [1- Rmax ] | NonASCIIDigit Digit: [0- Rmax ] | NonASCIIDigit GroupedNumeral: ( Non0Digit Digit ? Digit ? ( LocalGroupSeparator Digit Digit Digit )+ ) Numeral: ( ( Digit + ) | GroupedNumeral ) Integer: ( [-+]? ( Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix | LocalNegativePrefix Numeral LocalNegativeSuffix DecimalNumeral: Numeral | Numeral LocalDecimalSeparator Digit * | LocalDecimalSeparator Digit + Exponent: ( [eE] [+-]? Digit + ) Decimal: ( [-+]? DecimalNumeral Exponent ? ) | LocalPositivePrefix DecimalNumeral LocalPositiveSuffix Exponent ? | LocalNegativePrefix DecimalNumeral LocalNegativeSuffix Exponent ? HexFloat: [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?1+)? NonNumber: NaN | LocalNan | Infinity | LocalInfinity SignedNonNumber: ( [-+]? NonNumber ) | LocalPositivePrefix NonNumber LocalPositiveSuffix | LocalNegativePrefix NonNumber LocalNegativeSuffix Float: Decimal | HexFloat | SignedNonNumber
Whitespace is not significant in the above regular expressions.
Scanner: после nextInt "не видит" nextLine
Привет всем! Объясните, какая есть особенность у класса Scanner, из-за чего после того, как я введу в консоль число ( переменная scan.nextInt(); ), следующую строку в коде ( а именно строку scan.nextLine(); ) моя программа пропускает?
package TestPackage; import java.util.Scanner; public class Solution public static void main(String[] args) System.out.println("Фокус-покус! Введите две строки!!"); Scanner scan = new Scanner(System.in); String t1 = scan.nextLine(); System.out.println("Вы ввели строку: " + t1); String t2 = scan.nextLine(); System.out.println("Вы ввели строку: " + t2); System.out.println("Первая строка: " + t1 + ", а вторая: " + t2); System.out.println("Теперь введите число, а потом строку!!"); if (scan.hasNextInt()) int z1 = scan.nextInt(); System.out.println("Вы ввели число: " + z1 + ", теперь вводите строку!!"); > else System.out.println("Вы ввели строку. Так не честно :("); String t3 = scan.nextLine(); System.out.println("ТУТ ДОЛЖНА БЫТЬ СТРОЧКА. ГДЕ СТРОЧКА?!"); String t4 = scan.nextLine(); System.out.println("четвертую строчку мы увидели: " + t4); > >
Java scanner.nextLine() Method Call Gets Skipped Error [SOLVED]
Farhan Hasin Chowdhury
There's a common error that tends to stump new Java programmers. It happens when you group together a bunch of input prompts and one of the scanner.nextLine() method calls gets skipped – without any signs of failure or error.
Take a look at the following code snippet, for example:
import java.util.Scanner; public class Main < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("What's your name? "); String name = scanner.nextLine(); System.out.printf("So %s. How old are you? ", name); int age = scanner.nextInt(); System.out.printf("Cool! %d is a good age to start programming. \nWhat language would you prefer? ", age); String language = scanner.nextLine(); System.out.printf("Ah! %s is a solid programming language.", language); scanner.close(); >>
The first scanner.nextLine() call prompts the user for their name. Then the scanner.nextInt() call prompts the user for their age. The last scanner.nextLine() call prompts the user for their preferred programming language. Finally, you close the scanner object and call it a day.
It's very basic Java code involving a scanner object to take input from the user, right? Let's try to run the program and see what happens.
If you did run the program, you may have noticed that the program asks for the name, then the age, and then skips the last prompt for the preferred programming language and abruptly ends. That's what we're going to solve today.
Why Does the scanner.nextLine() Call Get Skipped After the scanner.nextInt() Call?
This behavior is not exclusive to just the scanner.nextInt() method. If you call the scanner.nextLine() method after any of the other scanner.nextWhatever() methods, the program will skip that call.
Well, this has to do with how the two methods work. The first scanner.nextLine() prompts the user for their name.
When the user inputs the name and presses enter, scanner.nextLine() consumes the name and the enter or the newline character at the end.
Which means the input buffer is now empty. Then the scanner.nextInt() prompts the user for their age. The user inputs the age and presses enter.
Unlike the scanner.nextLine() method, the scanner.nextInt() method only consumes the integer part and leaves the enter or newline character in the input buffer.
When the third scanner.nextLine() is called, it finds the enter or newline character still existing in the input buffer, mistakes it as the input from the user, and returns immediately.
As you can see, like many real life problems, this is caused by misunderstanding between the user and the programmer.
There are two ways to solve this problem. You can either consume the newline character after the scanner.nextInt() call takes place, or you can take all the inputs as strings and parse them to the correct data type later on.
How to Clear the Input Buffer After the scanner.nextInt() Call Takes Place
It's easier than you think. All you have to do is put an additional scanner.nextLine() call after the scanner.nextInt() call takes place.
import java.util.Scanner; public class Main < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("What's your name? "); String name = scanner.nextLine(); System.out.printf("So %s. How old are you? ", name); int age = scanner.nextInt(); // consumes the dangling newline character scanner.nextLine(); System.out.printf("Cool! %d is a good age to start programming. \nWhat language would you prefer? ", age); String language = scanner.nextLine(); System.out.printf("Ah! %s is a solid programming language.", language); scanner.close(); >>
Although this solution works, you'll have to add additional scanner.nextLine() calls whenever you call any of the other methods. It's fine for smaller programs but in larger ones, this can get very ugly very quick.
How to Parse Inputs Taken Using the scanner.nextLine() Method
All the wrapper classes in Java contain methods for parsing string values. For example, the Integer.parseInt() method can parse an integer value from a given string.
import java.util.Scanner; public class Main < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("What's your name? "); String name = scanner.nextLine(); System.out.printf("So %s. How old are you? ", name); // parse the integer from the string int age = Integer.parseInt(scanner.nextLine()); System.out.printf("Cool! %d is a good age to start programming. \nWhat language would you prefer? ", age); String language = scanner.nextLine(); System.out.printf("Ah! %s is a solid programming language.", language); scanner.close(); >>
This is a cleaner way of mixing multiple types of input prompts in Java. As long as you're being careful about what the user is putting in, the parsing should be alright.
Conclusion
I'd like to thank you from the bottom of my heart for taking interest in my writing. I hope it has helped you in one way or another.
If it did, feel free to share with your connections. If you want to get in touch, I'm available on Twitter and LinkedIn.
Farhan Hasin Chowdhury
Software developer with a knack for learning new things and writing about them
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.