1、假设文件中全为分数,则必为 "a/b" 的形式
2、建立处理 "a\b" 字符串的方法
public static double fraction(String str) {
int a = 0, b = 0;
boolean bool = true;
for (int i = 0; i < str.length(); i++) {
if (bool && str.charAt(i) != '/') {
a = a * 10 + str.charAt(i) - '0';
} else if (str.charAt(i) == '/')
bool = false;
else
b = b * 10 + str.charAt(i) - '0';
}
return (double) a / (double) b;
}
3、 主方法-运行示例
public class Fraction {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("fraction.txt");
Scanner input = new Scanner(file);
double sum = 0;
while (input.hasNext()) {
String line = input.next();
sum += fraction(line);
}
System.out.println(sum);
}