[英]How to read numbers from file and take actions on them in java?
this is my file information:这是我的文件信息:
mahdi aspanani 664 22.0 ali moghadasi 675 26.0
I want to read this information from file and count 22.0 + 26.0我想从文件中读取此信息并计数 22.0 + 26.0
how can I do this in java?我怎么能在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();
}
}
Assuming you mean the content of the file is structured like this:假设您的意思是文件内容的结构如下:
<string> <string> <int> <summand 1> <string> <string> <int> <summand 2>
and none of the strings contains spaces and both summands are doubles, you can do the following:并且没有一个字符串包含空格并且两个被加数都是双打,您可以执行以下操作:
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
}
Don't forget to put the name ofthe file instead of filename
.不要忘记输入文件
filename
而不是filename
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.