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); } }
java course)
Run the sample:aaaa bbbb cccc
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); } }
abcdefg abcdefg //剩下两行
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!