Home >Java >javaTutorial >How to use carriage return to continue inputting data in java

How to use carriage return to continue inputting data in java

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

Two methods for reading carriage return and line feed input in Java: Scanner class: nextLine() method reads the entire line of input to carriage return BufferedReader class: readLine() method reads the entire line of input to the end of the line

How to use carriage return to continue inputting data in java

Two ways to use Enter to continue inputting data in Java

1. Scanner class

Scanner class is a class in Java used to read data from user input. It provides a nextLine() method, which reads the entire line from standard input to the carriage return character.

Usage:

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

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的名字:");
        String name = scanner.nextLine();

        System.out.printf("你的名字是:%s\n", name);
    }
}</code>

2. BufferedReader class

The BufferedReader class is a character input stream that provides a The readLine() method reads a string from standard input to the end of the line.

Usage:

<code class="java">import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请输入你的年龄:");
        int age = Integer.parseInt(reader.readLine());

        System.out.printf("你的年龄是:%d\n", age);
    }
}</code>

Summary

The Scanner class and the BufferedReader class are both used to read data from user input effective tool. The Scanner class is better suited for reading strings, while the BufferedReader class is better suited for reading other data types such as integers and floating point numbers.

The above is the detailed content of How to use carriage return to continue inputting data 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