next () searches for space-separated tokens and returns the tokens in the order they are found. It doesn't matter if you change it because it returns the token after capturing the input from the scanner once.
nextLine () advances the current cursor to the beginning of the next line. Then, the skipped amount is output.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
String line = sc.nextLine();
System.out.println(str);
System.out.println(line);
sc.close();
}
}
What happens if you enter something like the one below for the code above?
input
1
abcde
First, sc.next () returns the very first token. 1 is entered in str. Here the cursor is between 1 and the line break.
input
1[Line feed code]
^
here
abcde
Now, running sc.nextLine () will move the cursor to the beginning of the next line.
input
1[Line feed code]
abcde
^
here
In other words, only the line feed code is read by nextLine ().
Recommended Posts