【发布时间】:2016-02-24 19:59:44
【问题描述】:
您好,我正在尝试编写一个程序,该程序从逗号分隔的文本文件中获取第三行,然后将其传递给 WeatherDataPoint 类中的 getData 方法,在该方法中,它将字符串拆分为逗号上的单独字符串。然后我希望将字符串变量 date 设置为 dataLine2[7] 的值。然后通过调用驱动程序类的 getDate 方法打印出日期字符串。
public class driver
{
public static void main(String[] args)
{
WeatherDataPoint weather = new WeatherDataPoint();
String dataLine1 = "";
String inputFile = "weatherdata.csv";
Scanner readFile = null;
try
{
readFile = new Scanner (new File(inputFile));
}
catch (FileNotFoundException ex)
{
System.out.println("Error file not found");
System.exit(1);
}
while (readFile.hasNextLine())
{
dataLine1 = readFile.nextLine();
weather.getData(dataLine1);
}
System.out.println(String.format("%s",weather.getDate()));
}
}
public class WeatherDataPoint {
private String date = "";
private String temperature;
public void getData(String dataLine1)
{
String [] dataLine2 = dataLine1.split(",");
date = dataLine2[7];
//long epoc = Long.parseLong(fields[DATE_POS]);
//Date d = new Date(epoc * 1000);
}
public String getDate()
{
//return String.format("%s", (date));
return date;
}
当我运行程序时出现错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
编辑这里是文本文件中的一行
"1452386100","1","5","29.002591800284698","77.91272888363851","78.21244075516647","86.27","49.8",,"99","0",,"0",,"0","0","49.53002056234984","49.8","49.8",,,,,,,,,,,,,,,,,,,,,"100",,,,,,,,,,,,
我在描述程序时犯了一个错误,我实际上想处理文件中的所有数据,但跳过前三行,抱歉造成混淆。将 dataLine[7] 更改为 dataLine[0] 也可以。
【问题讨论】:
-
错误信息不是不言自明吗?您在该行上的记录少于 8 条,因此是例外。使用您的调试器。或者将值打印到控制台。
-
如您所说,您问题中的代码从文件中获取所有行,而不是第三行。如果此代码有效,它只会打印文件最后一行的数据。如果你的文件只有三行,我想你会没事的,但我怀疑这就是你想要的......