Differences between scan. nextline () and scan. nextint () in the receiver method of the worker keyboard

Source: Internet
Author: User

Java code
  public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int a = sc.nextInt();        int b = sc.nextInt();        String s = sc.nextLine();        System.out.print("a: " + a + " b: " + b + " s: " + s);    }}

The following is my understanding. please correct me if there is anything wrong:

String S = SC. nextline ();
Here we read an empty string.

Because after entering the second number, you press Enter.
Assume that the second number you entered is: 5 (add a carriage return)
What the program actually receives is: 5/R/n
Nextint () scan to 5

Nextline (); Continue scanning. This method returns the remaining part of the current row until a line separator is encountered and does not include a line separator)
Because row separator/R is followed by row separator 5, only an empty string is scanned for nextline.

Java code
   public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int a = Integer.parseInt(sc.nextLine());        int b = Integer.parseInt(sc.nextLine());        String s = sc.nextLine();        System.out.print("a: " + a + " b: " + b + " s: " + s);    }}

This code can run successfully because SC. nextline () will automatically remove the row separators read.
So when you enter the second number: 5 (add a carriage return)
5/R/n
However, the program actually scans 5

When executing the code again:

Java code
   String s = sc.nextLine();

Because there is no data in the row, the program will be blocked until you enter the data again.

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.