How do I input a string with spaces in Java?

In Java, the Scanner class can be used to input strings with spaces. Here is a simple example code:

import java.util.Scanner;

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

        System.out.println("请输入带空格的字符串:");
        String input = scanner.nextLine();

        System.out.println("您输入的字符串是:" + input);

        scanner.close();
    }
}

In the code above, a string input with spaces can be obtained using the nextLine() method of Scanner. After the user finishes entering the string, they can press the Enter key to complete the input.

Leave a Reply 0

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