java - 如何标记文件并将数据输入到数组中?

标签 java arrays eclipse class token

我有一个用逗号分隔的信息文件,我需要对其进行标记并放入数组中。

该文件包含以下信息

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;
    }

它告诉我“i”和新的 Customer 是错误的,因为它“无法将 Customer 转换为 Customer[]”并且“i”在 token 中存在错误。

最佳答案

首先,您需要声明客户数组:

Customer[] cus = new Customer[count];

现在,程序知道它必须在内存上分配多少空间。 然后,您可以使用循环,但必须调用 Customer 类的构造函数,并向他提供创建新循环所需的所有信息:

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 中。但是您想将每个字符串的单个值提供给构造函数。

看一下字符串的 split 方法。 (How to split a string in Java)。

使用 split() 你可以像这样分割一行:

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

然后在 strArray 中您可以找到您的数据:

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

等等

关于java - 如何标记文件并将数据输入到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26434741/

相关文章:

eclipse - 如何阻止 Windows 上的 eclipse+git 破坏文件权限?

java - FileReader,如果文件不存在则创建文件

java - 集成测试 DBUnit NoSuchTableException Java

C# 在将值从文件读入数组时表现得很奇怪

javascript - 无法使用 localStorage 读取未定义的属性推送

java - CLI 中的 JUnit 测试等效项

Java模型更新多个 View

Java for 循环执行了两次

c# - 使用 SWIG 和 C# 时将 char* 缓冲区转换为字节数组

java - Eclipse 不显示错误或运行新代码