How to use Scanner in Java to retrieve a string

In Java, you can use the Scanner class to get user input for strings. Here is a simple example:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // 创建Scanner对象
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入字符串
        System.out.print("请输入一个字符串:");

        // 使用nextLine()方法获取用户输入的字符串
        String input = scanner.nextLine();

        // 打印输入的字符串
        System.out.println("你输入的字符串是:" + input);

        // 关闭Scanner对象
        scanner.close();
    }
}

In the previous example, we first create a Scanner object that reads user input from the standard input stream (System.in). We then use the nextLine() method to get the user’s input as a string and store it in a variable named “input”. Finally, we print out the user’s input string.

Please note that it is best to call the close() method after using the Scanner class to release resources.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds