![](/img/trans.png)
[英]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.