2014-10-17 66 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,也许考虑一些库如:

相关问题