我寫了一個程序來讀取文件。它正確讀取文件。我使用打印語句進行測試。但是在閱讀文件的最後一行之後,程序不會停止。它進入無限循環。我猜測我的while
循環會一直讀取空白字符作爲下一行。我不知道如何解決它。Java,文件讀取器,進入無限循環
如果我將break
放入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();
}
}
的可能重複[?基本的Java編程控制檯 - 可以使用hasNextLine讀取從控制檯輸入(http://stackoverflow.com/questions/5048290/java-basic-console-programming- can-use-hasnextline-to-read-inputs-from-console) – duffymo
看起來好像你從來沒有真正地使用過這條線,如果你在'else'中。所以'reader.hasNextLine()'總是如此,因爲你沒有前進。 –
是的,我認爲這是事實。我試着修復它在其他部分放一個break語句。但它不起作用。我該如何解決它? – user2942227