你可以使用Java的文件读取和数学运算来实现读取txt文件中的数字并求和的功能。以下是一个简单的示例代码:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileAndSumNumbers {
public static void main(String[] args) {
File file = new File("input.txt"); // 替换为你的txt文件路径
try {
Scanner scanner = new Scanner(file);
int sum = 0;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
sum += number;
} else {
scanner.next(); // 跳过非数字的部分
}
}
scanner.close();
System.out.println("Sum of numbers: " + sum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
在上述示例代码中,你需要将`"input.txt"`替换为你的txt文件的路径。程序会逐行读取文件中的内容,判断是否为整数,如果是则将其加入到求和的结果中。最后,输出求和结果。
请确保txt文件中的每个数字都位于单独的一行,否则可能会导致读取错误。
温馨提示:答案为网友推荐,仅供参考