The difference between next and nextline in the Java Sanner class

Source: Internet
Author: User

Next () differs from nextline () Next ():

1. Be sure to read the valid characters before you can end the input.

2. TheNext () method will automatically remove thewhitespace that is encountered before entering a valid character .

3. Enter only the valid characters before entering the blanks as delimiters or terminators.

Next () cannot get a string with a space.

Nextline ():

1 . Enter as the Terminator , meaning that the nextline () method returns all characters before the input carriage return.

2, you can get blank.

Example code:

import Java.util.Scanner;

Public class Scannertext {

Public Static void Main (string[] args) {

Scanner Scan=new Scanner (System. in);// receive data from the keyboard

int i=0;// defines an integer variable

float f=0.0f;// defines a floating-point variable

System. out. println (" input integer:");

if (Scan.hasnextint ()) {// determine if the input is an integer

I=scan.nextint ();// receive integer

System. out. println (" integer data:"+i);

}

Else {

Enter the wrong information

System. out. println (" input is not an integer! ");

}

Enter Decimal

System. out. println (" Enter decimal :");

if (Scan.hasnextfloat ()) {// determine if the input is a decimal

F=scan.nextfloat ();// Receive decimals

System. out. println (" decimal data is:"+f);

}

Else {

System. out. println (" the input is not a decimal!") ");

}

}

}

If you want to enter data of type int or float, it is also supported in the Scanner class, but it is best to use the Hasnextxxx () method for validation before entering, and then use NEXTXXX () to read , And more than two of the same

The difference between next and nextline in the Java Sanner class

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.