2015-01-06 6 views
0

이 간단한 Java 프로그램의 잘못된 점은 무엇입니까?java.util.NoSuchElementException : 파일에서 단어 읽기

내가 파일에서 단어를 읽고 다음과 같은 예외를 얻기 위해 시도하고 : 당신은 내가하지만 단어를 얻을 볼 수 있듯이

complication 
dilemma 
lavender 
issue 
happy 
weird 
Exception in thread "main" java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Scanner.java:907) 
    at java.util.Scanner.next(Scanner.java:1416) 
    at com.recrawl.util.ReadWordsTextfile.readWordsFromTextFile(ReadWordsTextfile.java:32) 
    at com.recrawl.util.ReadWordsTextfile.main(ReadWordsTextfile.java:13) 

, 나 또한 예외가. 다음 코드를 사용하고 있습니다 :

public static void main(String[] args) { 
    String path = "Word_and_phrases"; 
    ReadWordsTextfile r = new ReadWordsTextfile(); 
    r.readWordsFromTextFile(path); 
} 

public ArrayList<String> readWordsFromTextFile(String path) { 
    ArrayList<String> resultList = new ArrayList<String>(); 

    FileInputStream fileIn = null; 
    try { 
     fileIn = new FileInputStream(path); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    Scanner scan = new Scanner(fileIn); 
    while(scan.hasNextLine()) { 
     String word = scan.next(); 
     word = word.replace(",", ""); 
     System.out.println(word); 
     resultList.add(word); 
    } 
    scan.close(); 
    System.out.println(resultList.toString()); 
    return resultList; 
} 

정말 고맙습니다.

는 UPDATE

txt 파일의 내용은 다음과 같습니다

String word = scan.next(); 
+1

라인에서 작동하도록 구현 next()hasNextLine 동안 작업을 라인 (32)이다 구현? 그리고 당신이 읽고있는 파일은 무엇입니까? 관련 부분을 게시 할 수 있습니까? –

+0

@HamzahMalik Pls가 내 업데이트를 살펴 봅니다. – mrquad

+0

AFAIK를 읽을 문자가 더 이상 없을 때 NoSuchElementException이 발생합니다. 그래서 마지막 단어에 도달하면 충돌이 발생합니다. –

답변

2

사용 :

while(scan.hasNext()) 
그 IST

complication, dilemma, lavender, issue, happy, weird 

라인 (32) 대신

:

while(scan.hasNextLine()) 

hasNextnextLine()