I am creating a large array, where each element is the object Temperature(String dayMonthYear, String hour, double degrees, double speed)
I then take the dayMonthYear and hour and try to parse it into a date which is stored as an instance along with the degrees and speed (of wind).
Below is the code for making the array, the 86793 is the number of lines in the file
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;
}
Below is the contractor and the date parser
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;
}
Below is how the data I am trying to input looks like 1-Jan-2006 0:00 41.4 2
1-Jan-2006 1:00 39.8 1.9
[I have tried changing the inputs to something like
01-Jan-2006 03:00 41.5 1.7
but no avail]
The errors I get are
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)