[英]How do I take values read from a CSV file in java in one method and use them in another method?
[英]How to read numbers from file and take actions on them in java?
这是我的文件信息:
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
而不是filename
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.