为什么我不使用此 class 从 CSV 文件填充我的 arrayList
Why am I not populating my arrayList from CSV file with this class
我想使用 class 填充 arrayList 以压缩我的主要方法。所以,我想使用 "list" class 来填充我的 arrayList,然后在我的 main 中使用它来填充它。我不确定我遗漏了什么部分,但这是我在列表中的内容 class:
public class list {
List<Entry> People = new ArrayList<>();
BufferedReader br = null;
String csvFile = "employee_data.csv";
String line = "";
String cvsSplitBy = ",";
public void readFromFile(){
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] Labels = line.split(cvsSplitBy);
Entry entry = new Entry(Labels[0], Labels[1], Labels[2], Labels[3], Labels[4], Labels[5], Labels[6], Labels[7]);
People.add(entry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
然后这是主要的,我希望填充列表打印其大小:
public static void main(String[] args) {
System.out.print(People.size());
}
如果我通过 main 方法读取它,它工作正常。但是当我尝试将它移动到它自己的 class 时,无法解析列表 People。这是为什么?
因为 People
现在是 class list
的实例成员。为了访问它,您需要先创建一个 list
.
的实例
public static void main(String[] args) {
list myList = new list();
myList.readFromFile();
System.out.print(myList.People.size());
}
话虽这么说,但我会考虑在代码中修改很多东西。 Class 名称应以大写字母开头,class 变量应以小写字母开头。考虑通过 list
上的 getter 方法访问 People
,即
public class list {
...
public List<Entry> getPeople() {
return People;
}
}
请参阅 Google's style guide 以了解有关许多此类提示的详细信息。
我想使用 class 填充 arrayList 以压缩我的主要方法。所以,我想使用 "list" class 来填充我的 arrayList,然后在我的 main 中使用它来填充它。我不确定我遗漏了什么部分,但这是我在列表中的内容 class:
public class list {
List<Entry> People = new ArrayList<>();
BufferedReader br = null;
String csvFile = "employee_data.csv";
String line = "";
String cvsSplitBy = ",";
public void readFromFile(){
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] Labels = line.split(cvsSplitBy);
Entry entry = new Entry(Labels[0], Labels[1], Labels[2], Labels[3], Labels[4], Labels[5], Labels[6], Labels[7]);
People.add(entry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
然后这是主要的,我希望填充列表打印其大小:
public static void main(String[] args) {
System.out.print(People.size());
}
如果我通过 main 方法读取它,它工作正常。但是当我尝试将它移动到它自己的 class 时,无法解析列表 People。这是为什么?
因为 People
现在是 class list
的实例成员。为了访问它,您需要先创建一个 list
.
public static void main(String[] args) {
list myList = new list();
myList.readFromFile();
System.out.print(myList.People.size());
}
话虽这么说,但我会考虑在代码中修改很多东西。 Class 名称应以大写字母开头,class 变量应以小写字母开头。考虑通过 list
上的 getter 方法访问 People
,即
public class list {
...
public List<Entry> getPeople() {
return People;
}
}
请参阅 Google's style guide 以了解有关许多此类提示的详细信息。