无法解析方法’split’在’String’中

huangapple go评论173阅读模式
英文:

Cannot resolve method 'split' in 'String'

问题

以下是您的代码的翻译部分:

  1. 我正在尝试读取一个文件并将所有单词分割成单独的字符串
  2. 这是我的代码
  3. public String[] words(String fileName) throws Exception {
  4. BufferedReader reader = new BufferedReader(new FileReader(fileName));
  5. String word;
  6. String[] words;
  7. ArrayList<String> wordList = new ArrayList<>();
  8. while ((word = reader.readLine()) != null){
  9. words = word.split("\\s");
  10. for (String string : words)
  11. wordList.add(string);
  12. }
  13. return (String[]) wordList.toArray();
  14. }
  15. 出现错误的原因似乎是这一行
  16. `words = word.split("\\s");`
  17. 引发了一个错误指出"无法解析方法 'split' 在 'String' 中"但我不知道为什么

请注意,我已经将您代码中的HTML实体字符(如&quot;)还原为正常的双引号字符。

英文:

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

This is my code:

  1. public String[] words(String fileName) throws Exception {
  2. BufferedReader reader = new BufferedReader(new FileReader(fileName));
  3. String word;
  4. String[] words;
  5. ArrayList&lt;String&gt; wordList = new ArrayList&lt;&gt;();
  6. while ((word = reader.readLine()) != null){
  7. words = word.split(&quot;\\s&quot;);
  8. for (String string : words)
  9. wordList.add(string);
  10. }
  11. return (String[]) wordList.toArray();
  12. }

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

答案1

得分: 1

以下是翻译好的部分:

Imports used

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collections;
  1. public String[] words(String fileName) throws Exception {
  2. ArrayList<String> wordList = new ArrayList<>();
  3. String word;
  4. try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
  5. while ((word = reader.readLine()) != null) {
  6. Collections.addAll(wordList, word.split("\\s"));
  7. }
  8. }
  9. return wordList.toArray(String[]::new);
  10. }
英文:

You can write the same in a cleaner way

Imports used

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collections;
  1. public String[] words(String fileName) throws Exception {
  2. ArrayList&lt;String&gt; wordList = new ArrayList&lt;&gt;();
  3. String word;
  4. try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
  5. while ((word = reader.readLine()) != null) {
  6. Collections.addAll(wordList, word.split(&quot;\\s&quot;));
  7. }
  8. }
  9. return wordList.toArray(String[]::new);
  10. }

huangapple
  • 本文由 发表于 2020年7月22日 05:13:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63023190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定