java如何读入数字
使用 Scanner 类读取数字
在 Java 中,Scanner 类是最常用的方式之一,用于从控制台或文件中读取数字。以下是使用 Scanner 读取整数和浮点数的示例:
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取整数
System.out.print("请输入一个整数: ");
int intValue = scanner.nextInt();
// 读取浮点数
System.out.print("请输入一个浮点数: ");
double doubleValue = scanner.nextDouble();
System.out.println("输入的整数: " + intValue);
System.out.println("输入的浮点数: " + doubleValue);
scanner.close();
}
}
使用 BufferedReader 读取数字
如果需要更高的性能或从文件中读取数字,可以使用 BufferedReader 结合 InputStreamReader 读取输入,然后转换为数字类型:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadNumbersBuffered {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// 读取整数
System.out.print("请输入一个整数: ");
int intValue = Integer.parseInt(reader.readLine());
// 读取浮点数
System.out.print("请输入一个浮点数: ");
double doubleValue = Double.parseDouble(reader.readLine());
System.out.println("输入的整数: " + intValue);
System.out.println("输入的浮点数: " + doubleValue);
}
}
从文件中读取数字
如果需要从文件中读取数字,可以使用 Scanner 或 BufferedReader:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadNumbersFromFile {
public static void main(String[] args) throws FileNotFoundException {
Scanner fileScanner = new Scanner(new File("numbers.txt"));
while (fileScanner.hasNextInt()) {
int num = fileScanner.nextInt();
System.out.println("读取的整数: " + num);
}
fileScanner.close();
}
}
处理输入异常
读取数字时可能会遇到非法输入(如非数字字符),可以使用异常处理来确保程序健壮性:
import java.util.Scanner;
public class ReadNumbersWithException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("请输入一个整数: ");
int intValue = scanner.nextInt();
System.out.println("输入的整数: " + intValue);
} catch (Exception e) {
System.out.println("输入的不是有效整数!");
} finally {
scanner.close();
}
}
}
使用正则表达式验证输入
在读取数字前,可以使用正则表达式验证输入是否符合数字格式:
import java.util.Scanner;
public class ReadNumbersWithRegex {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数: ");
String input = scanner.nextLine();
if (input.matches("-?\\d+")) {
int intValue = Integer.parseInt(input);
System.out.println("输入的整数: " + intValue);
} else {
System.out.println("输入的不是有效整数!");
}
scanner.close();
}
}
使用 Java 8 的 Stream API 读取数字
如果从文件或列表中读取数字,可以使用 Java 8 的 Stream API:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class ReadNumbersWithStream {
public static void main(String[] args) throws IOException {
List<Integer> numbers = Files.lines(Paths.get("numbers.txt"))
.map(Integer::parseInt)
.collect(Collectors.toList());
System.out.println("读取的数字列表: " + numbers);
}
}
以上方法涵盖了从控制台、文件以及处理异常等多种场景下读取数字的方式。根据具体需求选择合适的方法即可。






