我正在创建一个大数组,其中每个元素都是对象 Temperature(String dayMonthYear, String hour, double degree, double speed)
然后我取 dayMonthYear 和 hour 并尝试将其解析为一个日期,该日期与度数和速度(风速)一起存储为一个实例。
下面是制作数组的代码,86793是文件中的行数
public Temperature[] readTemperatures(String filename) {
Temperature[] temp = new Temperature[86793];
File f = new File(filename);
Scanner scan;
int i = 0;
try {
scan = new Scanner(f);
while(scan.hasNextLine()) {
String dayMonthYear = scan.next();
String hour = scan.next();
double degrees = scan.nextDouble();
double speed = scan.nextDouble();
temp[i] = new Temperature(dayMonthYear, hour, degrees, speed);
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return temp;
}
下面是承包商和日期解析器
public Temperature(String dayMonthYear, String hour, double degrees, double speed) {
Date date = createDate(dayMonthYear, hour);
this.date = date;
this.temperature = degrees;
this.windspeed = speed;
}
// Method to create date
public static Date createDate(String date, String hour) {
Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String stringDate = date + " " + hour;
try {
returnDate = formatter.parse(stringDate);
} catch (Exception e) {
System.out.println("Invalid format: " + stringDate);
}
return returnDate;
}
下面是我尝试输入的数据看起来像 1-Jan-2006 0:00 41.4 2
2006 年 1 月 1 日 1:00 39.8 1.9
[我尝试将输入更改为类似
2006 年 1 月 1 日 03:00 41.5 1.7
但无济于事]
我得到的错误是
Invalid format: 01-Jan-2006 00:00
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at P10.readTemperatures(P10.java:22)
at P10.main(P10.java:61)
隔江千里
慕斯王
相关分类