This is essentially a best practices question about reading a file and making sure it follows a specific format. My current implementation works, but it's a while
loop with a bunch of if
/else
statements. I think it wouldn't be too readable for other developers.
/**
* Request the server to add the theatre details found in the file indicated by the path.
* The details include the theatre ID (unique across all theatres), the seating dimension, and
* the floor area (square metres). All theatres have as many seats in a row as they do rows, and the number of
* rows is indicated by the seating dimension.
* <p>
* <p>The file format is, each line consists of
* "THEATRE" "\t" theatre ID; "\t" seating dimension; "\t" floor area;
* <p>
* <p>If there is no file associated with the path, or the file format is incorrect, then
* the request fails.
*
* @param path The path indicating the file to use for the initialisation.
* @return An empty string if the initialisation is successful, otherwise a
* message explaining what went wrong beginning with ERROR (e.g. "ERROR incorrect format").
*/
public String initialise(String path)
{
//IO
File theatreFile = new File(path);
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(theatreFile);
}
catch (FileNotFoundException e)
{
return ResponseMessages.FILE_NOT_FOUND_ERR_MSG.getDescription();
}
String currentID = null;
int numRows;
int floorSpace;
/*Loop through input file tokens, check if format is correct and if so, create a theatre object
that corresponds with the given data. */
while(fileScanner.hasNext())
{
if(fileScanner.hasNext(THEATRE_NAME_MARKER))
{
fileScanner.next();
if(fileScanner.hasNext(THEATRE_CODE_MARKER))
{
currentID = fileScanner.next();
if (getTheatreIDs().contains(currentID))
{
return ResponseMessages.DUPLICATE_CODE_ERR_MSG.getDescription();
}
if (fileScanner.hasNextInt())
{
numRows = fileScanner.nextInt();
if (fileScanner.hasNextInt())
{
floorSpace = fileScanner.nextInt();
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
}
else
{
return ResponseMessages.FILE_FORMAT_ERR_MSG.getDescription();
}
Theatre newTheatre = new Theatre(currentID, numRows, floorSpace);
theatres.add(newTheatre);
}
fileScanner.close();
return ResponseMessages.FILE_FOUND_SUCCESS_MSG.getDescription();
}
Additionally, here's an example of what an input file may look like:
THEATRE T2 10 400
THEATRE T1 7 200
THEATRE T3 12 600
THEATRE 215 21 1200