这是我的文件信息:
mahdi aspanani 664 22.0
ali moghadasi 675 26.0
我想从文件中读取此信息并计数22.0 + 26.0
如何在Java中执行此操作?
Scanner input;
String myFileName = "......";
try {
input = new Scanner(new File(myFileName));
double sum = 0;
while (input.hasNextLine()) {
String line = input.nextLine();
String[] vals = line.split("\\s+");
sum += Double.parseDouble(vals[3]);
}
System.out.println("sum = " + sum);
} catch (Exception e) {
e.printStackTrace();
}
}
假设您的意思是文件内容的结构如下:
<string> <string> <int> <summand 1> <string> <string> <int> <summand 2>
而且所有字符串都不包含空格,并且两个加数均为双精度,可以执行以下操作:
try(BufferedReader br=new BufferedReader(new FileReader(filename))){
String[] split=br.readLine().split(" ");
double result=Double.parseDouble(split[3])+Double.parseDouble(split[7]);
//do with it whatever you want
}catch(IOException e){
e.printStackTrace();//or do something else or don't catch it and add it to the signature
}
不要忘了用文件名代替filename
。