It is a very common operation to dynamically input data from the console, perform various processing on the data, and then output the data. Now we will give a systematic introduction to the data input method:
Call of Scanner class
Related methods:
hasNext()
Determine whether there is the next paragraph after the current scanning position in the scanner.
hasNextLine()
Returns true if another line exists in this scanner's input.
next()
Find and return the next complete token from this scanner.
nextLine()
This scanner executes the current line and returns skipped input information.
nextInt()
Return the integer data scanned by the console.
Related video tutorial sharing: java learning video
Code example:
package FIRST_Chapter; import java.util.Scanner; public class TestScanner { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("请输入字符串:"); while (true) { String line = s.nextLine(); if (line.equals("ok")) break; System.out.println(">>>" + line); } } }
Result demonstration:
The difference between next() and nextLine() methods
next() method must read valid characters before it can end the input. Valid characters must be entered The next() method will automatically remove the previously encountered terminators such as the space bar, Tab key or Enter key. Only after entering a valid character, the next() method will remove the space bar, Tab key or Enter key entered afterwards. Keys, etc. are treated as delimiters or terminators.
Simply put, next() finds and returns the next complete token from this scanner. The complete tag is preceded and followed by input information that matches the delimited pattern, so the next method cannot get a string with spaces.
The end character of the nextLine() method is only the Enter key, that is, the nextLine() method returns all the characters before the Enter key, and it can get a string with spaces.
For example, the following program:
package FIRST_Chapter; import java.util.Scanner; class test{ public static void main(String[] Args){ Scanner sc= new Scanner(System.in); System.out.println("请输入一段数据"); String str =sc.next(); System.out.println("用next输入的语句"+str); String str1 =sc.nextLine(); System.out.println("用nextLine输入的语句"+str1); //sc.nextLine();//如果下面注释行想用nextLine的话,就要注意加上这句话 } }
Output result:
The above is the detailed content of How to let Java get the string entered by the user. For more information, please follow other related articles on the PHP Chinese website!