Home >Java >javaTutorial >How to use Enter to continue inputting text in Java

How to use Enter to continue inputting text in Java

下次还敢
下次还敢Original
2024-04-21 02:42:321066browse

How to use Enter to continue inputting text in Java

Direct answer:
In Java, you can use nextLine() Method reads a string with spaces from the keyboard until the Enter key is pressed.

Detailed expansion:

nextLine() method belongs to the java.util.Scanner class, which is used to read from Read data from the input stream. When you use this method to read a string, it reads a sequence of characters from the keyboard until it encounters the Enter key (\n).

Code example:

<code class="java">import java.util.Scanner;

public class InputExample {

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

        // 使用 nextLine() 方法读取带空格的字符串,直到按下回车键
        System.out.println("请输入您的姓名:");
        String name = scanner.nextLine();

        // 使用 nextLine() 方法读取带空格的字符串,直到按下回车键
        System.out.println("请输入您的地址:");
        String address = scanner.nextLine();

        // 输出输入的数据
        System.out.println("您的姓名:" + name);
        System.out.println("您的地址:" + address);
    }
}</code>

In the above example:

  • Scanner scanner = new Scanner(System.in); Creates a Scanner object that will read data from standard input (usually the keyboard).
  • String name = scanner.nextLine(); Use the nextLine() method to read a string with spaces from the keyboard and store it in name variable.
  • String address = scanner.nextLine(); Use the nextLine() method to read another string with spaces from the keyboard and store it in address variable.
  • Finally, the System.out.println() statement outputs the input data.

The above is the detailed content of How to use Enter to continue inputting text in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn