"Java" Scanner class Nextint cannot read input after using nextline

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.