2014-10-17 72 views
0

我有一個由逗號分隔的信息文件,我需要對它進行標記並放入數組。如何標記文件並將數據輸入到數組中?

該文件具有信息,如

14299,Lott,Lida,22 Dishonest Dr,Lowtown,2605 
14300,Ryder,Joy,19 Happy Pl,Happyville,2701 

等等。我需要將這些由逗號分隔的信息進行tekonize。我不知道如何寫出令牌生成器代碼來使它分開。我設法計算了文檔中的行數;

File customerFile = new File("Customers.txt"); 
    Scanner customerInput = new Scanner(customerFile); 
    //Checks if the file exists, if not, the program is closed 
    if(!customerFile.exists()) { 
     System.out.println("The Customers file doesn't exist."); 
     System.exit(0); 
    } 
    //Counts the number of lines in the Customers.txt file 
    while (customerInput.hasNextLine()) { 
     count++; 
     customerInput.nextLine(); 
    } 

而且我也有我將放置標記化信息的類;

public class Customer { 
    private int customerID; 
    private String surname; 
    private String firstname; 
    private String address; 
    private String suburb; 
    private int postcode; 
public void CustomerInfo(int cID, String lname, String fname, String add, String sub, int PC) { 
    customerID = cID; 
    surname = lname; 
    firstname = fname; 
    address = add; 
    suburb = sub; 
    postcode = PC; 
} 

但在此之後,我不知道如何將信息放入客戶的數組。我試過這個,但是不對;

for(i = 0; i < count; i++) { 
     Customer cus[i] = new Customer; 
    } 

它告訴我「我」和新的客戶是錯誤的,因爲它「不能客戶轉化爲客戶[]」和「我」在標記的錯誤。

+0

的Java或Javascript?你的問題可能只有其中一個標籤。 – jfriend00 2014-10-17 23:33:05

回答

1

首先,你需要聲明的客戶陣:現在

Customer[] cus = new Customer[count]; 

,在PROGRAMM知道,它有多大的空間分配上的內存。 然後,你可以用你的循環,但你必須調用類客戶的構造,並給了他所有的信息,則需要創建一個新的:

for(i = 0; i < count; i++) { 
    Customer cus[i] = new Customer(cID, lname, fname, add, sub, PC); 
} 

你會問自己有關的另一件事是,我如何從字符串/行中獲取數據到數組中。

爲此,您應該將所有行寫入ArrayList中。喜歡這個。

ArrayList<String> strList = new ArrayList<String>(); 
while (customerInput.hasNextLine()) { 
    count++; 
    strList.add(customerInput.nextLine()); 
} 

現在您將所有行作爲字符串存儲在ArrayList中。但是你想給每個字符串的單個值給你的構造函數。

查看來自Strings的拆分方法。 (How to split a string in Java)。

在拆分()可以拆分這樣一行:然後

String[] strArray = "word1,word2,word3".split(","); 

在strArray你可以找到你的數據:

strArray[0] would have the value "word1"; 
strArray[1] = "word2"; 

0

如果是一個CSV文件,而不是一個簡單的逗號分隔flie,也許考慮一些庫如:

相關問題