打印从文件填充的ArrayList时NoSuchElementException

时间:2013-12-08 03:28:49

标签: java arraylist

当我尝试运行此并调用此特定方法时,我得到NoSuchElementException。在将其更改为ArrayList之前,它工作正常,而不是直接使用Scanner从文件中读取/打印。

以下是我选择选项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和/或如何解决的问题?

1 个答案:

答案 0 :(得分:0)

可能会有一些事情发生......我会尝试这个

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.
  }
}