2015-09-30 49 views
-2

因此,我無法讓我的程序不在我處拋出NoSuchElement異常。當我輸入機主信息,它拋出的第二任主人後異常無論哪個老闆,我輸入:在寫入.txt文件時遇到問題

Jones; 221 Smith St; Arlington; Texas; 76019 

Smith; 7345 Lane Rd; Dallas; Texas; 75000 

Willis; 596 Dale Lane; Fort Worth; Texas; 76123 

這裏是我的代碼:

import java.util.Formatter; 
import java.util.Scanner; 
import java.util.NoSuchElementException; 
import java.util.StringTokenizer; 

public class WriteFile 
{ 

public static void main(String[] args) 
{ 

    Formatter output; 
    try 
    { 
     output = new Formatter("owners.txt"); 
     System.out.println("file accessed"); 

     System.out.println("Please enter owner information. Separate  information with semicolons please:"); 
     Scanner input = new Scanner(System.in); 

     while(input.hasNext()) 
     { 
      try 
      { 

       String owner = input.nextLine(); 
       String[] tokens = owner.split(";"); 

       output.format("%s %s %s %s %d%n",input.next(), input.next(), input.next(), input.next(),input.nextInt()); 
      } 

      catch(NoSuchElementException ee) 
      { 
       System.out.println("Error on input. Please try again."); 
       input.nextLine(); 
      } 
     } 

     output.close(); 
    } 
    catch(Exception e) 
    { 
     System.out.println("Error working with file"); 
    } 
} 
} 

謝謝大家的幫助!

+0

您應該在'format'調用中使用'tokens'變量,並且不要在'catch'中調用'nextLine'。還要考慮你如何期待循環結束。 – Andreas

+0

您能否更新您的問題與您在此嘗試的是什麼?你想寫入輸入到文件或只是格式化它顯示到控制檯?就目前而言,您的代碼幾乎有太多問題需要回答。 –

回答

0

這裏的問題:

output.format("%s %s %s %s %d%n",input.next(), input.next(), input.next(), input.next(),input.nextInt()); 

的調用讀取下一個令牌讀什麼,因爲你剛纔input.readLine()已經吞噬了整條生產線。您應該在格式化程序中使用您的tokens[]對象。