【问题标题】:NoSuchElement Exception in Thread in TextFile Program文本文件程序中的线程中没有此类元素异常
【发布时间】:2021-09-29 05:29:30
【问题描述】:
嗨。我遇到了异常错误的问题。我不知道出了什么问题。但请帮我解决这个问题。我正在尝试将文件中的数据存储到 ArrayList 并在 ArrayList 中显示数据。在这里,我附上了我的代码和数据Code and data source。
【问题讨论】:
标签:
java
arrays
file
arraylist
text-files
【解决方案1】:
出现 NoSuchElementException 是因为您正在调用 input.nextToken(); 而输入没有任何标记。这是由于您的文件 listbook.txt 的最后一个空行。通过删除这一行,异常应该不会出现。
一种适当的方式可能是确保您有足够的令牌来检索给定行的所有字段。
public class TextFile
{
public static void main(String[] args)
{
try
{
FileReader read = new FileReader("C:\\Users\\ogawi\\Downloads\\listbook.txt");
BufferedReader bf = new BufferedReader(read);
Book B = new Book();
ArrayList<Book> bookList = new ArrayList<Book>();
String data = null;
StringTokenizer input = null;
while((data = bf.readLine()) != null)
{
input = new StringTokenizer(data,";");
//we ensure that we have enough tokens to retrieve all fields
if(input.countTokens() == 6)
{
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
}
}
//This part of code has been moved outside the while loop
//to avoid to print the total content of the array each time
//an element is added
int count=0;
for(int i=0;i<bookList.size();i++)
{
B = (Book)bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
bf.close();
}
catch(FileNotFoundException fnf)
{ System.out.println(fnf.getMessage());}
catch(EOFException eof)
{ System.out.println(eof.getMessage());}
catch(IOException io)
{ System.out.println(io.getMessage());}
finally
{ System.out.println("System end here..TQ!!");}
}
}
【解决方案2】:
这个问题是由于没有书籍信息的额外行:
你可以看到上图中的第31和32行。
要解决此问题,您可以添加一个 if 条件 data.contains(";") 。文本文件有 ; 分隔符,如果我们检查条件,如果给定行有 ; 分隔符,则不会导致问题。
while ((data = bf.readLine()) != null) {
if (data.contains(";")) {
input = new StringTokenizer(data, ";");
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
int count = 0;
for (int i = 0; i < bookList.size(); i++) {
B = (Book) bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
}
}
这是成功执行代码的屏幕截图。