93 lines
2.9 KiB
Java
93 lines
2.9 KiB
Java
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
import java.util.NoSuchElementException;
|
|
import java.util.Scanner;
|
|
|
|
/**
|
|
* Parses the temperature and date from a file given as a string to the file
|
|
* @author Isaac Shoebottom (3429069)
|
|
*/
|
|
|
|
public class TemperatureParser {
|
|
private Scanner sc;
|
|
private int counterDateTime = -1;
|
|
private int counterTemperature = -1;
|
|
private double temperature;
|
|
private String date;
|
|
|
|
/**
|
|
* Constructor for the parser
|
|
* Measures the index of the date/time and temperature in the csv file
|
|
* @param filename The filename of the csv file to be parsed.
|
|
*/
|
|
TemperatureParser(String filename) {
|
|
try {
|
|
sc = new Scanner(new File(filename), "UTF-8").useDelimiter("\",\"");
|
|
} catch (FileNotFoundException exception) {
|
|
System.out.println("File not found, the file might have been typed incorrectly");
|
|
System.out.print("Use tab to autocomplete a filename when in the same directory as the program");
|
|
System.exit(1);
|
|
}
|
|
int counter = 1;
|
|
String field;
|
|
while (sc.hasNext() && counterTemperature == -1 | counterDateTime == -1) {
|
|
field = sc.next();
|
|
if (field.equals("Date/Time (LST)"))
|
|
counterDateTime = counter;
|
|
if (field.equals("Temp (°C)"))
|
|
counterTemperature = counter;
|
|
counter++;
|
|
}
|
|
sc.nextLine();
|
|
|
|
}
|
|
|
|
|
|
/**
|
|
* Parses a line of a csv and gets the date/time and temperature
|
|
* @throws NoSuchElementException When a line is incomplete or a field is empty in the csv spreadsheet this error is thrown
|
|
*/
|
|
void parseLine() throws NoSuchElementException {
|
|
String line = sc.nextLine();
|
|
Scanner scanDate = new Scanner(line).useDelimiter("\",\"");
|
|
Scanner scanTemp = new Scanner(line).useDelimiter("\",\"");
|
|
try {
|
|
for (int i = 1; i < counterDateTime; i++) {
|
|
scanDate.next();
|
|
}
|
|
date = scanDate.next();
|
|
for (int i = 1; i < counterTemperature; i++) {
|
|
scanTemp.next();
|
|
}
|
|
temperature = scanTemp.nextDouble();
|
|
}
|
|
catch (NoSuchElementException exception) {
|
|
System.out.println("Invalid entry at: " + date);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Checks if there is a value next
|
|
* @return boolean if there is a next value true if not false
|
|
*/
|
|
boolean parseHasNext() {
|
|
return sc.hasNext();
|
|
}
|
|
|
|
/**
|
|
* Gets there temperature that was most recently parsed
|
|
* @return The temperature that was most recently parsed as a double
|
|
*/
|
|
public double getTemperature() {
|
|
return temperature;
|
|
}
|
|
|
|
/**
|
|
* Gets the date that was most recently parsed
|
|
* @return The date/time that was most recently parsed
|
|
*/
|
|
public String getDate() {
|
|
return date;
|
|
}
|
|
}
|