我的目标:将 CSV 文件中的所有数据解析为数组列表
问题:有一行全部为“null”值,但我设置为解析 double ,因此,出现 NumberFormatException
我尝试过的:我打算通过捕获 NumberFormatException 并将 null 替换为前一天的价格来解决这个问题,但它不起作用。
我的问题: (1) 下面代码中如何设置它解析arraylist中的前一个元素? (2) 我是否需要更改代码的整个结构来标记数组列表中的每个元素,以便我可以专门将 null 设置为前一个元素?
谢谢。
//import file, file path
Scanner inputFile = checkFile("C:\\data\\3988.HK.csv");
//Build up ArrayList to store data from file
ArrayList<Date>Date = new ArrayList<Date>();
ArrayList<Double>Open = new ArrayList<Double>();
ArrayList<Double>High = new ArrayList<Double>();
ArrayList<Double>Low = new ArrayList<Double>();
ArrayList<Double>Close = new ArrayList<Double>();
// Read the first line
String line = inputFile.nextLine();
// Add data to the 1st arraylists from the file
while(inputFile.hasNext())
{
String[] data = inputFile.nextLine().split(",");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try
{
Date.add(sdf.parse(data[0]));
}
catch(ParseException e)
{
System.out.println("Invalid format in the file.");
}
try
{
Open.add(Double.parseDouble(data[1]));
High.add(Double.parseDouble(data[2]));
Low.add(Double.parseDouble(data[3]));
Close.add(Double.parseDouble(data[4]));
}
catch(NumberFormatException e)
{
System.out.print("Non-numeric data found in the file.\nThe invalid record will be replaced the previous day prices.");
Open.add(Open.previous());
High.add(High.previous());
Low.add(Low.previous());
Close.add(Close.previous());
}
}
最佳答案
有一点是,第一行的条件将失败,因为第一行没有前一个
第二件事是,如果值为 null,则实际上应该输入 0,而不是上一个
解决方案是您需要检查行位置,然后使用上一个,还需要在单独的函数中定义 try catch,然后调用它,因为这对于一个值将失败,并且会影响所有 4 个值。强>
尝试下面的代码
try
{
Date.add(sdf.parse(data[0]));
}
catch(ParseException e)
{
System.out.println("Invalid format in the file.");
}
Open.add(getLongFromData(data[1]));
High.add(getLongFromData(data[2]));
Low.add(getLongFromData(data[3]));
Close.add(getLongFromData(data[4]));
为值(value)创建一个函数
private long getLongFromData(String data)
{
long longValue = 0;
try
{
longValue = Double.parseDouble(data);
}
catch(NumberFormatException e)
{
longValue = 0;
}
return longValue;
}
关于Java解析数组列表中的前一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59082673/