java如何输入
使用Scanner类进行输入
Scanner类是Java中最常用的输入工具,适用于从控制台或文件读取数据。需要导入java.util.Scanner包。
基本语法:
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt(); // 读取整数
String str = scanner.next(); // 读取字符串(空格分隔)
String line = scanner.nextLine(); // 读取整行
scanner.close(); // 关闭Scanner
注意事项:
nextLine()会读取换行符,若之前调用过nextInt()等非行读取方法,需额外调用一次nextLine()消耗残留的换行符。- 使用后需关闭资源(
close()),避免内存泄漏。
使用BufferedReader类进行输入
BufferedReader适合高效读取大量数据,需配合InputStreamReader使用。需导入java.io.BufferedReader和java.io.InputStreamReader。
基本语法:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine(); // 读取整行
int num = Integer.parseInt(line); // 转换为整数
br.close(); // 关闭资源
优势:
- 性能优于Scanner,尤其处理大规模输入时。
- 需手动处理类型转换(如
Integer.parseInt())。
控制台输入示例
以下是一个完整的控制台输入输出示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入整数:");
int num = scanner.nextInt();
System.out.print("请输入字符串:");
String str = scanner.next();
System.out.println("整数:" + num + ",字符串:" + str);
scanner.close();
}
}
文件输入示例
若需从文件读取数据,可使用FileReader或Scanner:
import java.io.File;
import java.util.Scanner;
public class FileInput {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
输入异常处理
建议通过try-catch处理输入异常(如类型不匹配):
try {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数字:");
int num = scanner.nextInt();
System.out.println("输入的数字是:" + num);
scanner.close();
} catch (Exception e) {
System.out.println("输入错误,请确保输入的是整数!");
}
通过以上方法,可以灵活应对不同场景的输入需求。







