Different java versions will have different features. For example, the Scanner in Java is not locked in previous versions and is specifically used to obtain input data. Here we have to mention commonly used string input. There are two methods in the Scanner class: next and nextLine. Next, we will provide detailed explanations of these two methods of obtaining strings.
1.next method
If the entered valid characters are followed by a space, next() will use the space as the terminator. Therefore, if there are spaces in the middle of the input string, the complete string cannot be obtained using the next method.
import java.util.Scanner; public class TestScanner1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Receive data from the keyboard System.out.println("Receive in next mode:"); // Determine whether there is still input if (scan.hasNext()) { // Next method receives string String str1 = scan.next(); System.out.println("The input data is: " + str1); } } }
You can see that the java string is not output.
2.nextLine method
nextLine() uses Enter as the end character. That is to say, the nextLine() method returns all the characters before the carriage return.
import java.util.Scanner; public class TestScanner2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // NextLine method receives string System.out.println("nextLine method receives: "); // Determine whether there is still input if (scan.hasNextLine()) { //Receive data from keyboard String str2 = scan.nextLine(); System.out.println("The input data is: " + str2); } } }
The above is how the Scanner class in Java obtains strings. After reading the article, you will find that next obtains part of the string, while nextLine outputs the character content before the carriage return. Everyone should pay attention to the final result output .