2013-12-08 2 views
0

이것을 실행하고이 특정 메서드를 호출하려고하면 NoSuchElementException이 표시됩니다. Scanner으로 직접 파일을 읽거나 인쇄하는 대신에 ArrayList으로 변경하기 전에 정상적으로 작동했습니다. 스레드에서NoSuchElementException 파일에서 채워진 ArrayList를 인쇄 할 때

예외 "주"java.util.NoSuchElementException
java.util.Scanner.throwFor (알 수없는 소스)에서
: 여기

내가 옵션 2 [ ArrayList]을 선택할 때 그것이 말하는 것입니다 java.util.Scanner.next (알 소스)에 version4.version4.readDisplay에서
(version4.java:79) version4.version4.main (version4.java:27)

에서
17,451,515,

내 코드 :

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 및/또는 방법을 해결하기 위해를 일으키는 원인을 알아?

+0

을 시도 할 것 ... 몇 가지 일이 벌어있을 수 있습니다. –

+0

그 부분은 예외를 던지고있는 것이 아니라 여전히 동일한 것을 가지고 있으며 Elliot의 수정 후에도 잘 작동합니다. – Corey

답변

0

내가 항상 예외 : NoSuchElementException를 던질 기회를 가질 것)을 iter.hasNext (내부 iter.next()를 여러 번 추가이

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

이유를 정확하게 이해하지는 마세요. 감사! – Corey

관련 문제