【发布时间】:2021-04-04 10:35:22
【问题描述】:
我正在尝试制作一个 Java 程序,其中电视节目数据的 CSV 文件的内容存储在 TVShow 对象数组中。我让 TVShow 类对每个 CSV 文件的类别都有一个变量。
当我尝试跑步时,我不断收到NoSuchElementException。我尝试打印出文件的内容,它可以工作,但我不知道程序出了什么问题。
编辑: 根据@gthanop 的建议,我更改了下面的 Main.java 代码。现在的问题是数组的所有元素都是 CSV 文件的第一行。
public class TVShow
{
String name;
String yearPremiered;
String numOfSeasons;
String numOfEpisodes;
String network;
String genre;
String maleLead;
String femaleLead;
public TVShow(String name, String yearPremiered, String numOfSeasons, String numOfEpisodes, String network, String genre, String maleLead, String femaleLead)
{
this.name = name;
this.yearPremiered = yearPremiered;
this.numOfSeasons = numOfSeasons;
this.numOfEpisodes = numOfEpisodes;
this.network = network;
this.genre = genre;
this.maleLead = maleLead;
this.femaleLead = femaleLead;
}
}
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws Exception
{
TVShow[] array = new TVShow[20]; //There are 20 rows of TV show data in the CSV file
Scanner read = new Scanner(new File("tv_shows.csv"));
read.nextLine();
int row = 0;
read.useDelimiter(",|\n");
while (read.hasNext())
{
String name = read.next();
String yearPremiered = read.next();
String numOfSeasons = read.next();
String numOfEpisodes = read.next();
String network = read.next();
String genre = read.next();
String maleLead = read.next();
String femaleLead = read.next();
while (row < 20)
{
array[row] = new TVShow(name, yearPremiered, numOfSeasons, numOfEpisodes, network, genre, maleLead, femaleLead);
row++;
}
}
read.close();
for (int i = 0; i < 20; i++)
{
System.out.println(array[i]);
}
}
}
【问题讨论】:
-
考虑使用 CSV 库而不是滚动您自己的 CSV 解析。
-
@MarkRotteveel 这是家庭作业的一部分,所以我不能使用外部库:(