从文本文件中我试图连续获得第3组数据(type = double),然后将其求和以得到总数。我的问题是我无法弄清楚如何使用缓冲文件阅读器从一行中获取特定数据。我知道如何获得这条线,但解析数据是个谜。我已将我的代码放在下面,以防它可能有助于提供更多背景信息。谢谢!
编辑:请耐心等待我。我确实在学习Java的第一个月内。我必须使用缓冲读卡器。这是一个学校项目。我应该使用“拆分”吗?如果是这样,我可以将“下一个拆分”或某些内容存储到数组中吗?Int string(?) double int
PropertyID Type Cost AgentID --(Not in the file. The file only has the data)
100000 Farm 500000.00 101
100001 Land 700000.00 104
package overview;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.nio.*;
public class Overview {
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
int count = 0;
double totalCost=0.00;
ArrayList<Double> propertyID = new ArrayList();
//Get file name
Scanner console = new Scanner(System.in);
System.out.print ("Please enter file name: ");
String inputFileName = console.next();
File inputFile = new File(inputFileName);
// Get the object of DataInputStream
FileInputStream fstream = new FileInputStream(inputFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null)
{
double x = Double.parseDouble(line.split(" ")[]);
propertyID.add(x);;
totalCost = Double.parseDouble(line.split(" ")[8]);
count++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
System.out.println("Total properties in list: " + count + "\n"+ "The total cost is: " +totalCost);}
}
}
答案 0 :(得分:0)
这是一个有效的例子(没有文件):
private static final String data = "100000 Farm 500000.00 101\n100001 Land 700000.00 104";
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
double totalCost = 0;
BufferedReader reader = new BufferedReader(new StringReader(data));
String line;
try {
while ((line = reader.readLine()) != null) {
StringTokenizer stok = new StringTokenizer(line);
int propertyId = Integer.parseInt(stok.nextToken());
String type = stok.nextToken();
double cost = Double.parseDouble(stok.nextToken());
int agentId = Integer.parseInt(stok.nextToken());
totalCost += cost;
count++;
}
// close input stream
}
catch (Exception e) {
e.printStackTrace();
}
finally {
System.out.println("Total properties in list: " + count + "\nTotal cost is: " + totalCost);
}
}