First of all, we know that the methods next() and nextLine() in the Scanner class in Java are used to obtain user input.
(Recommended tutorial:java introductory tutorial)
Let’s take a look at the difference between the two:
next() will not get the character before / After the space/Tab key, only the characters are obtained. Start to obtain characters (not counting before and after characters) until the space/Tab key/Enter key is encountered; nextLine() will obtain the space/Tab key before and after the character, and end when the Enter key is encountered.
Example:
import java.util.Scanner; import java.util.Vector; public class Main{ public static void main(String args[]) { Scanner reader=new Scanner(System.in); String s1=reader.nextLine(); String s2=reader.next(); System.out.println(s1); System.out.println(s2); } }
Run result:
import java.util.Scanner; import java.util.Vector; public class Main{ public static void main(String args[]) { Scanner reader=new Scanner(System.in); String s1=reader.next(); // String ss=reader.nextLine(); String s2=reader.nextLine(); System.out.println(s1); System.out.println(s2); } }(Recommended tutorial:
java course)
Run the sample:aaaa bbbb ccccBecause there is a space after aaaa, next is not needed, so next After reading, the leftovers bbbb cccc were picked up by nextLine The solution is to add the nextLine() noted in the above code
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner reader=new Scanner(System.in); String s1=reader.next(); String s2=reader.nextLine(); System.out.println(s1); System.out.println(s2); } }Running results:
abcdefg abcdefg //剩下两行Input The carriage return program after abcdefg has ended, and then abcdefg and two line feeds are output. The reason is because nextLine absorbs the carriage return after next. Be very careful that the two nextLines should not be connected together. This will not happen when using next, because the first requirement absorbed by next is the character, and the last requirement is the space, Tab key, and Enter key.
The above is the detailed content of What is the difference between next() and nextLine() in java?. For more information, please follow other related articles on the PHP Chinese website!