java的循环输入怎么写

循环输入可以通过以下两种方式实现:使用 Scanner 类提供 nextLine() 方法,利用 while 循环持续读取输入,直到用户输入特定退出条件。使用 BufferedReader 类提供 readLine() 方法,利用 while 循环持续读取字符流,同样直到用户输入退出条件。

Java 循环输入

如何写循环输入

1. 使用 Scanner 类:

Scanner 类提供了一个 nextLine() 方法,用于从控制台读入一行字符串。要实现循环输入,可以使用 while 循环不断从控制台读取输入,直至用户输入特定的退出条件。

示例代码:

import java.util.Scanner;

public class LoopingInput {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(Sy

stem.in); while (true) { System.out.println("Enter a line of text (or type 'exit' to quit): "); String input = scanner.nextLine(); if (input.equalsIgnoreCase("exit")) { break; } // 处理输入 } } }

2. 使用 BufferedReader 类:

BufferedReader 类提供了 readLine() 方法,用于从字符流中读入一行文本。类似于 Scanner 类,可以使用 while 循环不断从字符流中读取输入。

示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class LoopingInputBufferedReader {

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            System.out.println("Enter a line of text (or type 'exit' to quit): ");
            String input = reader.readLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            // 处理输入
        }
    }
}