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

Java 循环输入
如何写循环输入
1. 使用 Scanner 类:
Scanner 类提供了一个 nextLine() 方法,用于从控制台读入一行字符串。要实现循环输入,可以使用 while 循环不断从控制台读取输入,直至用户输入特定的退出条件。
立即学习“Java免费学习笔记(深入)”;
示例代码:
<code class="java">import java.util.Scanner;
public class LoopingInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.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;
}
// 处理输入
}
}
}</code>2. 使用 BufferedReader 类:
BufferedReader 类提供了 readLine() 方法,用于从字符流中读入一行文本。类似于 Scanner 类,可以使用 while 循环不断从字符流中读取输入。
示例代码:
<code class="java">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;
}
// 处理输入
}
}
}</code>以上就是java的循环输入怎么写的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号