An issue in which the Nextint () method of the Java scanner class cannot be stopped in a loop

Source: Internet
Author: User
Let's look at the exact words in the Java API documentation:

当扫描器抛出 InputMismatchException 时,该扫描器不会传递导致该异常的标记,因此可以通过其他某种方法来获取或跳它。                    这是java API文档中的原话。

In fact it means: "'
If you enter the a character when the Nextint method executes, and you do not successfully parse an integer at this time, your input will not be ignored. Because it might be able to be parsed by other formats.
Then your program entered a, an exception, number is assigned a value of 100, start the next loop, but then the data buffer in the last time you entered a still, and did not clear, then continue to resolve a, or error, so this process has been repeated.

So there are a number of ways to solve this, for example:

                        现在你要改的是,出现错误把这次的输入清除,只要在catch中,加一句:input.next()就搞定了!,其实意思就是说把上一次的缓存清除就行了。                    也可以将Scanner写在try里面

An issue in which the Nextint () method of the Java scanner class cannot be stopped in a loop

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.