you are trying to consume a token that is not there. you do a number of next() calls without checking if there is next. in your case, I suspect a newline at the end of your file gives you an empty line as input. the scanner will see a new line, but as it doesn't contain tokens, calling "next()" will cause an error.
the same would happen if you have empty lines between blocks in your file.
one thing you can use is:
public boolean hasNext(String pattern)
instead of
next()
this will let you do a lookahead without consuming a token.
so instead of:
String MessageType = reader.next();
int IsAdd = MessageType.compareToIgnoreCase("A");
int IsCancel = MessageType.compareToIgnoreCase("X");
// .... left out other classes
//if the type of order is add order to existing Order Book
if (IsAdd == 0){
// .. do stuff
}
you can do something like:
if (reader.hasNext("A") {
reader.next(); // consume A
int ts = reader.nextInt(); // get id
// ... etcetera
} else if (reader.hasNext("X") {
}
I would also recommend you use nextInt() instead of nextString and then calling parseInt
One other thing: you can even make your code better to read by doing:
if (reader.hasNext("A") {
handleAddition(reader);
}
and then later on define a method that only handles this case. your main method will look like:
try
{
while (reader.hasNextLine())
{
if (reader.hasNext("A")) {
handleAdd(reader);
} else if (reader.hasNext("X")) {
handleCancel(reader);
} else if (reader.hasNext("D")) {
handleDelete(reader);
} else if (reader.hasNext("E")) {
handleExecute(reader);
} else if (reader.hasNext("R")) {
handleReplace(reader);
} else {
// unexpected token. pretty sure this is the case that triggers your exeception.
// basically log as info and ignore.
reader.nextLine();
}
}
}
finally
{
reader.close();
}
Now your method is nice and short, and all the specific actions are taken in methods with their own name.
the only thing I'm not 100% about if it it's good practice to consume A, X, R, etc... inside the main loop, or the actual handler method. I prefer to consume inside the method personally.
hope it helps.