Home  >  Article  >  Java  >  How to read input string in java

How to read input string in java

下次还敢
下次还敢Original
2024-03-28 17:24:39955browse

Java读取输入字符串的方法有多种:标准输入流System.inScanner类BufferedReader类

How to read input string in java

Java 读取输入的字符串

方法

Java 提供多种方法来从用户读取字符串:

  • 标准输入流
  • Scanner 类
  • BufferedReader 类

标准输入流

System.in 字段表示标准输入流。使用 nextLine() 方法可以读取一行文本:

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

public class Main {
    public static void main(String[] args) {
        InputStreamReader reader = new InputStreamReader(System.in);
        String input = reader.readLine();
        System.out.println(input);
    }
}</code>

Scanner 类

Scanner 类提供了更方便的方法来读取输入:

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.println(input);
    }
}</code>

Scanner 类还支持读取其他数据类型,比如整数和浮点数。

BufferedReader 类

BufferedReader 类是一种底层读取器,提供了更高级别的功能:

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

public class Main {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = reader.readLine();
        System.out.println(input);
    }
}</code>

readLine() 方法会读取整行文本,包括换行符。可以使用 trim() 方法删除开头的和结尾的空格。

The above is the detailed content of How to read input string 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