0

what`s wrong with this simple java program?

I am trying to read words from a file and get the following exception:

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)

As you can see I get the words however, I also get an exception. I am using the following code:

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

I really appreciate your answers!

UPDATE

The content of the txt file looks like that:

complication, dilemma, lavender, issue, happy, weird

Line 32 ist that:

    String word = scan.next();
Carol.Kar
  • 4,830
  • 22
  • 98
  • 199

1 Answers1

2

Use :

while(scan.hasNext())

Instead of:

while(scan.hasNextLine())

hasNext is implemented to work with next() while hasNextLine is implemented to work with nextLine()

panagdu
  • 2,055
  • 1
  • 21
  • 35