我的代码示例如下:
File myFile = new File("C:\\Windows\\Temp\\fileName.csv");
try {
Scanner myScanner = new Scanner(myFile);
while(myScanner.hasNextLine()) {
String data = myScanner.nextLine();
String[] fields = data.split(",");
name = fields[0];
age = Integer.parseInt(fields[1]);
birthday = fields[2];
storeVisitDate = fields[3];
}
Person myPerson = new Person(name,age,birthday,storeVisitDate);
}
}
我有一个单独的类“ Person”,该类根据CSV文件的输入实例化一个对象。
我的任务是准备一个输出,该输出在一行上生成一个人的姓名,年龄,生日和商店访问日期,但是,如果此人有多个商店访问日期,则仅应在以下位置显示商店访问日期:下一行。
如何将当前行与下一行进行比较以查看其名称是否相同?另外,我不允许创建任何ArrayLists / Lists。
.CSV文件内容的 样本:.CSV文件内容的样本
谢谢。
人员类别:
public class Person{
private String name;
private int age;
private String birthday;
private String dateOfVisit;
public Person(String data)
{
String[] info = data.split(",");
name = info[0];
age = Integer.parseInt(info[1]);
birthday = info[2];
dateOfVisit = info[3];
}
}
这是一个经典的数据处理练习,使我想起了30多年前的COBOL编程。基本算法如下:
在您的情况下,如果两个Person
具有相同的值,则它们是相同的name
。
根据上述算法,您需要保存最后的Person
详细信息。
下面是实现的Java代码。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Person {
private String name;
private int age;
private String birthday;
private String dateOfVisit;
public Person(String data) {
String[] info = data.split(",");
name = info[0];
age = Integer.parseInt(info[1]);
birthday = info[2];
dateOfVisit = info[3];
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBirthday() {
return birthday;
}
public String getDateOfVisit() {
return dateOfVisit;
}
public String toString() {
return String.format("%s %d %s ", name, age, birthday);
}
/**
* @param args
*/
public static void main(String[] args) {
File myFile = new File("C:\\Windows\\Temp\\fileName.csv");
Person lastPerson = null;
int count = 0;
try (Scanner myScanner = new Scanner(myFile)) {
while (myScanner.hasNextLine()) {
String data = myScanner.nextLine();
Person p = new Person(data);
if (lastPerson == null || !lastPerson.getName().equals(p.getName())) {
if (count == 1) {
System.out.println(lastPerson.getDateOfVisit());
}
System.out.print(p);
count = 1;
lastPerson = p;
}
else {
if (count == 1) {
System.out.println();
System.out.println(lastPerson.getDateOfVisit());
}
count++;
System.out.println(p.getDateOfVisit());
}
}
// Print the visit date of the last person in the CSV file.
if (count == 1) {
System.out.println(lastPerson.getDateOfVisit());
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
请注意,您需要关闭Scanner
。上面的代码是通过try-with-resources实现的
使用您提供的样本数据,以上代码的输出如下。
Aliza Burn 20 01/01/2000
07/20/2018
08/15/2016
04/14/2014
Edward Chase 45 02/14/1974
05/05/2009
06/20/2014
Penny Lane 15 06/20/2004
03/13/2018
05/06/2018
Josef Hunt 89 09/28/1930 08/21/2019
变量计数的目的是什么?
@ royalducky28处理文件的第一行和最后一行。尝试从代码中删除它,然后运行修改后的代码,看看会发生什么。