我写了一个程序来读取文件。它正确读取文件。我使用打印语句进行了测试。但是在读取文件的最后一行之后,程序并没有停止。它进入一个无限循环。我猜我的while
循环一直在读取空白字符作为下一行。我不知道如何解决它。
如果我将 abreak
放入该else
部分,它只会读取第一行并跳出while
循环。我不确定为什么。
请帮帮我。
这是代码:
public static void InterpretMessageFromFile() throws FileNotFoundException{
File inputfile = new File("FilePath");
Scanner reader = new Scanner(inputfile);
try
{
while (reader.hasNextLine())
{
//if the type of order is add order to existing Order Book
if (reader.hasNext("A")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
//int id = Integer.parseInt(retrieve_id ,2); // for binary file
String or_side = reader.next();
String retrieve_share = reader.next();
int share = Integer.parseInt(retrieve_share);
// int share = Integer.parseInt(retrieve_share, 2); //for binary file
String retrieve_price = reader.next();
int price = Integer.parseInt(retrieve_price);
//int price = Integer.parseInt(retrieve_price, 2); //for binary file
System.out.println("Add Order : Id is " + id );
AddOrderToExistingBook.AddNewOrder(id, ts, or_side, share, price);
}
//if it is cancel order
else if (reader.hasNext("X")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
System.out.println("Cancel Order : Id is " + id + " time stamp is : " + ts );
//int id = Integer.parseInt(retrieve_id, 2); //for binary file
//String retrieve_share = reader.next();
// int share = Integer.parseInt(retrieve_share, 2); // need to add back later, removing it for testing purposes
CancelOrder.CancelPartOfOrder(id, ts);
}
//if it is delete order
else if (reader.hasNext("D")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts, 2);
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id, 2);
DeleteOrder.DeleteOrderFromBook(id, ts);
}
else{
// unexpected token.
// basically log as info and ignore.
}
}
}
finally
{
reader.close();
}
}