The difference between the next and nextline usages of Java's scanner class

Source: Internet
Author: User
Tags first string

Next (); Gets the string from the console, if the string contains a space, only gets the first string to be received. For example: Enter Hello I am a chinese!, receive only hello.

Nextline (); Gets a string from the console, which can contain spaces, with a carriage return as the receive end flag. For example: input hello I am a chinese!, received is hello I am a chinese!.


How do you get Next (); methods can also receive strings that include spaces like nextline ()?

There is a Hasnext () method in the scanner class, note that this method is a blocking method that represents each time a string is read from the console. In order to be able to end the input, you can specify a string to end the input, such as "quit" to indicate the end of the input. The implementation code is as follows:


String s;

while (!sc.hasnext ("Quit"))

{

s = Sc.next ();

System.out.println (s);

}


In this way, next () has a function similar to nextline (), and the input "quit" string guarantees the end of the input state.


This article is from the Java Technology Alliance blog, so be sure to keep this source http://simoniu.blog.51cto.com/2566344/1587828

The difference between the next and nextline usages of Java's scanner class

Related Article

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.