英文:
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实体字符(如"
)还原为正常的双引号字符。
英文:
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.
答案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<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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论