[英]java.util.NoSuchElementException of ArrayList from Text file
[英]NoSuchElementException when printing my ArrayList that was populated from a file
當我嘗試運行此方法並調用此特定方法時,我收到了NoSuchElementException
。 在將其更改為ArrayList
之前,它工作得很好,而不僅僅是使用Scanner
直接從文件讀取/打印。
這是我選擇選項2 [ ArrayList
]時的內容:
線程“主”中的異常java.util.NoSuchElementException
在java.util.Scanner.throwFor(未知來源)
在java.util.Scanner.next(未知源)
在version4.version4.readDisplay(version4.java:79)
在version4.version4.main(version4.java:27)
我的代碼:
public class version4
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
boolean exit = false;
while (!exit)
{
System.out.println("1 Find an item.\n2 Display all items.\n3 Update item.\n4 Save item to disk.\n5 Quit.");
int choice = in.nextInt();
switch (choice){
case 1: System.out.println("You chose to find an item from file."); findItem(); break;
case 2: System.out.println("You chose to display all items."); readDisplay(); break;
case 3: System.out.println("You chose to update an item."); itemUpdate(); break;
case 4: System.out.println("You chose to save an item to disk."); itemAdd(); break;
case 5: exit = true; break;
default: System.out.println("That is not a valid option."); break;
}
}
System.out.println("Goodbye.");
}
public static void readDisplay() throws FileNotFoundException
{
// Open input file:
System.out.println("Reading 'read_record.txt'");
FileReader reader = new FileReader("read_record.txt");
Scanner fin = new Scanner(reader);
String str = null;
ArrayList<String> dvdfile = new ArrayList<String>();
while((str = fin.next()) != null){
dvdfile.add(str);
}
Iterator iter = dvdfile.iterator();
while (iter.hasNext())
{
String sku = (String) iter.next();
String title = (String) iter.next();
String length = (String) iter.next();
System.out.printf("%-10s %-15s %10s %n",sku,title,length);
}
// Close file:
fin.close();
}
}
有人知道是什么導致了NoSuchElementException
和/或如何解決?
可能會發生一些事情...我會嘗試這個
if (fin != null && fin.hasNext()) { // do we have a scanner, is there anything to read?
while (fin.hasNext()) { // while there's something to read...
str = fin.next(); // read it.
if (str == null) { // end if it's null?
break;
}
dvdfile.add(str); // otherwise add it.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.