java - 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;
解决方案
行。我有几条评论。首先 - 你真的需要 '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);
}
推荐阅读
- javascript - 按下按钮后动态添加新文本框不起作用 - Angular
- token - 在我的 BEP20 Token 代码中使用 import 语句会影响我的未来吗?
- asp.net-web-api - WebAPI URL 未按预期路由
- sql - 我需要一种方法来查找一行是否有值,如果有,那么我需要根据另一个值对所有行进行分组
- javascript - 发生特定事件后,如何让 div 更改其背景图像?
- r - 取一列并转换为 R 中每个 id 的计数
- neo4j - Neo4j 为密码查询返回无值
- excel - 将最后 n 个单元格相加,不包括空格和输入数字时的移位
- git - Git log --all --oneline --decorate --graph 不显示带有星号行的分支
- python - 如何在 Pandas 中将多个列表保存到多行中?