【问题标题】:How to tokenize a file and input the data into an array?如何标记文件并将数据输入到数组中?
【发布时间】:2014-10-17 23:26:45
【问题描述】:

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

该文件包含诸如

之类的信息
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”和新客户是错误的,因为它“无法将客户转换为客户[]”并且“i”在令牌中有错误。

【问题讨论】:

  • Java 还是 Javascript?您的问题可能只有其中一个标签。

标签: java arrays eclipse class token


【解决方案1】:

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

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 中得到了所有行作为字符串。但是您想将每个 String 的单个值提供给您的构造函数。

看看 Strings 中的 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"; 

等等

【讨论】:

    【解决方案2】:

    如果它是一个 CSV 文件而不是一个简单的逗号分隔的文件,也许可以考虑一些类似的库:

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      相关资源
      最近更新 更多