當我嘗試運行此並調用此特定方法時,我得到NoSuchElementException
。它工作得很好,然後我將其更改爲ArrayList
,而不是直接從文件Scanner
直接讀取/打印。NoSuchElementException當打印從文件填充我的ArrayList
以下是它說當我選擇選項2 ArrayList
]:
異常線程 「main」 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
和/或如何解決?
加入iter.next()多次的iter.hasNext(內部)將始終有機會拋出NoSuchElementException異常。 –
這部分沒有拋出異常,我仍然保持原樣,並且在Elliot修復後仍能正常工作。 – Corey