首页 > 解决方案 > java - 读取文件并创建数组

问题描述

我必须遵循特定的格式并使用扫描仪。我知道有更好的方法,但这是一个要求,我是 java 新手并试图解决这个问题。有一个包含客户姓名、出生日期和其他信息的文件。我需要计算文件中的条目数,然后文件需要根据文件条目数创建一个数组并将数组转换为字符串数组。我需要做更多的代码,但我被困在这部分。必须使用 try/catch。

public class Customers {
  //////// MAIN ////////
  public static void main(String[] args) {
    File file = new File("customers.txt");
    int numEntries = countCustomers(file);
    Person[] customers = readIntoArray(file, numCustomers);
    int min = locateBirthdate(customers);
    System.out.println("Birthdays this month: " + customer[mon].getBirthdate());

  }
  //* Counts customers in the file.//
  public static int countCustomers(File f) {
    int i = 0;
    try {
      Scanner scan = new Scanner(f);
      while (scan.hasNextLine()) {
        i++;
        scan.nextLine();
      }
    } catch (Exception e) {
      System.out.println("Check filename.");
    }

    return i;
  }
  //read data into array and convert into string array

  public static Customer[] readIntoArray(File f, int num) {
      //num = countCustomers(f);
      num = 0;
      try {
        Scanner input = new Scanner(f);
        Customer[] birth = new Customer[num];
        String[] strBirth = new String[num];
        while (num < countCustomers(f)) {
          strBirth[num] = input.nextLine();
          birth[num] = makeCustomer(strBirth[num]);
          num++;
          System.out.println(num);
        }

      } catch (Exception e) {
        System.out.println("Error");
      }
      return null;

标签: javaarraysstringreadfile

解决方案


行。我有几条评论。首先 - 你真的需要 'strBirth' 数组吗?看起来你只写元素而不是从数组中读取。第二 - 'readIntoArray' 方法总是返回 null。此外,您计算了两次客户,但只有一个就足够了。那么,你真的需要一个有客户的阵列吗?由于您使用数组,因此您需要准确了解客户数量,因此您需要扫描文件两次。如果使用 ArrayList,则只需扫描一次文件。

我已经修复了下面代码中的问题。

public class Customers {
  //////// MAIN ////////
  public static void main(String[] args) {
    File file = new File("customers.txt");
    Person[] customers = readIntoArray(file, numCustomers);
    int numEntries = customers.length;
    int min = locateBirthdate(customers);
    System.out.println("Birthdays this month: " + customer[mon].getBirthdate());

  }

  public static Person[] readIntoArray(File f, int num) {
      List<Customer> customers = new ArraList<>();
      try {
        Scanner input = new Scanner(f);
        String[] strBirth = new String[num];
        while (scan.hasNextLine()) {
          customers.add(makeCustomer(scan.nextLine()));
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      return customers.toArray(Person[]::new);
  }

推荐阅读