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

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

Cannot resolve method 'split' in 'String'

问题

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

我正在尝试读取一个文件并将所有单词分割成单独的字符串

这是我的代码

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

出现错误的原因似乎是这一行
`words = word.split("\\s");`
引发了一个错误指出"无法解析方法 'split' 在 'String' 中"但我不知道为什么

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

英文:

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&lt;String&gt; wordList = new ArrayList&lt;&gt;();
    while ((word = reader.readLine()) != null){
        words = word.split(&quot;\\s&quot;);
        for (String string : words)
            wordList.add(string);
    }

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

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

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);
}
英文:

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&lt;String&gt; wordList = new ArrayList&lt;&gt;();
    String word;
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        while ((word = reader.readLine()) != null) {
            Collections.addAll(wordList, word.split(&quot;\\s&quot;));
        }
    }
    return wordList.toArray(String[]::new);
}

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:

确定