How to use the useDelimiter() method of the Scanner class to set the delimiter of the user input string
The Scanner class is a very useful tool class in Java, which allows processing from standard input, files and strings Reading becomes very easy. The Scanner class provides many useful methods, one of which is the useDelimiter() method, which is used to set the delimiter used when inputting. Use this method to conveniently read user input strings separated by a specified delimiter.
The following is an example that demonstrates how to set the delimiter using the useDelimiter() method of the Scanner class.
import java.util.Scanner; public class ScannerDelimiterExample { public static void main(String[] args) { // 创建Scanner对象,并指定输入来源为标准输入System.in Scanner scanner = new Scanner(System.in); // 使用useDelimiter()方法设置分隔符为逗号和空格 scanner.useDelimiter("[,\s]+"); // 提示用户输入一串以逗号和空格分隔的字符串 System.out.print("请输入一串以逗号和空格分隔的字符串:"); // 读取用户输入的字符串 while (scanner.hasNext()) { String word = scanner.next(); System.out.println("读取的单词:" + word); } // 关闭Scanner对象 scanner.close(); } }
In the above example, we first create a Scanner object and use System.in to set the input source to standard input. Then, we call the useDelimiter() method and set the delimiter to the regular expression "[,\s]", which represents a comma and one or more consecutive spaces. After setting the separator like this, we can easily get each word separated by commas and spaces at once.
Next, we use the System.out.print() method to prompt the user to enter a string separated by commas and spaces. Then, through a while loop combined with the hasNext() and next() methods, each word entered by the user is read one by one, and the System.out.println() method is used to output the read words.
Finally, we must remember to close the Scanner object to release resources.
After running the above code, the user can enter a string separated by commas and spaces. The program will read and output each word until the input is complete. For example, if the user enters "Hello, world! How are you today?", the program will output the following content:
读取的单词:Hello 读取的单词:world! 读取的单词:How 读取的单词:are 读取的单词:you 读取的单词:today?
By using the useDelimiter() method of the Scanner class, we can easily set the limit of the user input string. delimiter, allowing for more flexibility in handling user input. Whether reading standard input, reading a file, or reading a string, you can use this method to set the appropriate delimiter to meet your specific needs.
The above is the detailed content of How to use the useDelimiter() method of the Scanner class to set the delimiter of the user input string. For more information, please follow other related articles on the PHP Chinese website!