我想從「DataFile.txt」文件中讀取數據,但在一個程序中我有2個整數,那麼如何傳遞整數(假設「天」和「tprice」變量是整數)使用StringTokenizer?Java:使用StringTokenizer添加整數
private void readDataFileAndDisplay()
{
String allRecord=""; // all details of customer
try
{
Scanner in = new Scanner (new FileReader ("DataFile.txt")); //open file
String myEntry = "" ;
String name ="";
String ID="";
String roomType ="";
String meal="";
String days="";
String tprice="";
while (in.hasNextLine())
{
myEntry = in.nextLine();
StringTokenizer st = new StringTokenizer (myEntry, ",");
while (st.hasMoreTokens())
{
name = st.nextToken();
ID = st.nextToken();
name = st.nextToken();
roomType = st.nextToken();
meal = st.nextToken();
days = st.nextToken();
tprice =st.nextToken();
myList.add (new Customer (name, ID, roomType, meal, days, tprice));
}
} // end of while loop
in.close(); // close file
} catch (IOException ex)
{
System.out.println ("file loading failed.");
}
}
我也曾嘗試parseInt函數,如:
int Intdays = Integer.parseInt (st.nextToken());
int IntTprice = Integer.parseInt (st.nextToken());
,但編譯它顯示下面的異常後:
看不到錯誤(破碎的圖像),但看起來好像你的'hasMoreTokens()'邏輯需要一點思考。你會有每條記錄多於一條記錄嗎?也許提供一些示例數據? – radimpe 2012-04-25 10:17:35
我認爲數字之間有空格? – 2012-04-25 10:21:14
問題不在於Intger或String。您的令牌循環有問題。您檢查 – Edge 2012-04-25 11:16:32