2013-09-25 155 views
0

我似乎遇到了一些麻煩讓我的代碼在這裏正常運行。這是應該做的是它應該從文本文件中讀取,並找到每行上的項目的名稱,數量和價格,然後格式化結果。這裏棘手的一點是,這些項目的名稱由兩個單詞組成,因此這些字符串必須與數量整數和價格雙倍相區分。雖然我能夠得到這個工作,但我遇到的問題是在文本文件的最後,在最後一個項目的價格之後。這是給我一個java.util.NoSuchElement Exception: null,我似乎無法通過它。有人可以幫我解決問題嗎?該錯誤是在thename = thename + " " + in.next();NoSuchElement異常錯誤

while (in.hasNextLine()) 
     { 
      String thename = ""; 

      while (!in.hasNextInt()) 
      { 
       thename = thename + " " + in.next(); 
       thename = thename.trim(); 
      } 
      name = thename; 
      quantity = in.nextInt(); 
      price = in.nextDouble(); 

     } 
+2

你需要檢查是否有下一次調用之前更多的令牌()。 – Thilo

回答

0

你需要確保Name quantity price字符串格式正確。字符串中可能沒有足夠的標記。要檢查是否有足夠的令牌,名稱:

while (!in.hasNextInt()) 
     { 
      thename = thename + " "; 
      if (!in.hasNext()) 
       throw new SomeKindOfError(); 
      thename += in.next(); 
      thename = thename.trim(); 
     } 

你不必拋出一個錯誤,但你應該有某種形式的代碼來處理這個問題妥善根據您的需求。

0

的問題是在你的內心while循環的邏輯:

while (!in.hasNextInt()) { 
    thename = thename + " " + in.next(); 
} 

在英語中,這個說:「雖然有沒有提供一個int,讀取下一個標記」。測試沒有幫助檢查下一個動作是否會成功。

您不檢查是否有下一個令牌可供閱讀。

考慮更改測試一個,使操作安全:

while (in.hasNext()) { 
    thename = thename + " " + in.next(); 
    thename = thename.trim(); 
    name = thename; 
    quantity = in.nextInt(); 
    price = in.nextDouble(); 
}