First, we introduce, in the Java language, for string input, because the scanner.next () function can not enter the space and carriage return, at this time, we have to use scanner.nextline () to solve such problems ,
In the process of use, we will find Nextint () and nextline used together, this problem occurs:
After you enter an int data, it is output, and the string is not entered at all ...
Then went online to check some information, read some of the forum, understand some of the principles, tidy up a bit.
First of all, scanner is a scanner that scans data to scan and read data in a buffer in memory, and the data we enter in the console is also stored in the buffer waiting for the scanner to read. This scanner in the scanning process to judge the basis of the stop is "blank character", Space Ah, enter AH what is counted as a blank character.
The Nextint () method will read the preceding data when it is scanned to whitespace, but will leave the whitespace "\ r" in the buffer, but the nextline () method will clean up the scanned whitespace when scanning.
By understanding the characteristics and differences of the two methods, we know what the above code is all about and how to solve it. Like the code above the Nextint () method left in the buffer "\ r", and then the Nextline () method to go to the buffer to find the data when the first saw "\ r", and then the "\ R" Scan received in, and in the buffer to clear out. In fact, the Nextline () method was executed and did not execute.
Know the principle, then the solution is relatively simple:
At the end of Nextint (), add a sentence of Scan.nextline ().
"Java" Scanner class Nextint cannot read input after using nextline