-1

I am trying to read a file and split all the words into separate Strings.

This is my code:

 public String[] words(String fileName) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String word;
    String[] words;
    ArrayList<String> wordList = new ArrayList<>();
    while ((word = reader.readLine()) != null){
        words = word.split("\\s");
        for (String string : words)
            wordList.add(string);
    }

    return (String[]) wordList.toArray();
}

For some reason the line: words = word.split("\\s"); is causing an error "Cannot resolve method 'split' in 'String'" but I have no idea why.

  • 2
    You'll likely need to provide more details, since it's a string function. Do you have anything else called `String` in your code? – Dave Newton Jul 21 '20 at 21:18
  • No, I don't have. – Anthony Chalk Jul 21 '20 at 21:21
  • 2
    Then it's (more or less) impossible to have this error unless something is very wrong with your Java install. Please include the complete code and Java installation details. – Dave Newton Jul 21 '20 at 21:23
  • 1
    your code compiles and runs ok. it's impossible to have that error – aran Jul 21 '20 at 21:23
  • 1
    What IDE do you use? Have you checked your JDK setting? – Andrew Vershinin Jul 21 '20 at 21:26
  • okay sorry for some reason I had the following import: import com.sun.org.apache.xpath.internal.operations.String; I didn't notice it and I have no idea how it got there - but after deleting it everything works now – Anthony Chalk Jul 21 '20 at 21:28
  • It appears my IDE imported the wrong String class for some reason. Figured out how to resolve it from these two questions: https://stackoverflow.com/questions/43273812/string-cannot-be-applied-to-com-org-apache-xpath-internal-operations-string https://stackoverflow.com/questions/41379178/intellij-2016-3-2-keeps-changing-string-import-to-com-sun-org-apache-xpath-inter – Anthony Chalk Jul 21 '20 at 21:38

1 Answers1

1

You can write the same in a cleaner way

Imports used

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public String[] words(String fileName) throws Exception { 
    ArrayList<String> wordList = new ArrayList<>();
    String word;
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        while ((word = reader.readLine()) != null) {
            Collections.addAll(wordList, word.split("\\s"));
        }
    }
    return wordList.toArray(String[]::new);
}
Lovesh Dongre
  • 1,294
  • 8
  • 23