The difference between nextIntnextLinenext in Java

Asked 2 years ago, Updated 2 years ago, 42 views


import java.util.Scanner;

public class Demo11720_2 {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int n=in.nextInt(); //
        String numA=in.next(); 


        System.out.println(n);
        System.out.println(numA);

    }

}
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int n=in.nextInt(); 
    String numA=in.nextLine(); 

    System.out.println(n);
    System.out.println(numA);

}

}

Since nextInt does not remove open characters, I understand that even if you enter 1 (Enter)12345 in the second nextLine example, the entry will go into the nextLine's input. But why does the first next example output 12345 as it is when you enter 1 (Enter) 12345?

Does next not receive input for enter?

Thank you in advance for your response on time.

java

2022-09-22 19:15

2 Answers

It's not an exact answer, it's an inference.

Scanner.next() or the derivative method Scanner.nextInt() reads the input in token (=word). So I don't read spaces, line breaks, which are the delimiters that separate tokens.

On the other hand, Scanner.nextLine() is read by line. That means you're going to read the opening letter together.

At this point in time, you can assume that:

If you enter 1 (Enter) in the first next(), next() will read up to 1. Enter seems to remain somewhere (such as a buffer. In the second next(), the enter is viewed as a delimiter and ignored, so wait for the next input.

If you enter 1 (Enter) in next(), next() will read up to 1 as above. Enter will remain somewhere at this time. Enter somewhere here is read from nextLine(). Because nextLine() doesn't care about delimiters. And once you've read it, you don't have any additional input opportunities.


2022-09-22 19:15

Thank you for your reply. :)


2022-09-22 19:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.