gpt4 book ai didi

java - 从每一行中获取第一个词?

转载 作者:行者123 更新时间:2023-12-03 23:14:26 25 4
gpt4 key购买 nike

很难从每一行中提取第一个词。任何想法为什么它输出空白文件?

程序将以下文本作为输入:

abecedism   word created from the initials of words in a phrase
ablaut variation in root vowel of words to change meaning
acronym word formed from initial letters of another word
acrophonic using a symbol for the initial sound of a thing
acroteleutic phrase or words at the end of a psalm
adversative word or phrase expressing opposition

目标是让结果看起来像这样:

abecedism   
ablaut
acronym
acrophonic
acroteleutic
adversative

目前的代码如下:

public static void main(String args[]) {
String fileNameOutput = "OutputFile.txt";
String fileName = "InputWords.txt";
Charset cs = Charset.defaultCharset();
try (BufferedReader bReader = Files.newBufferedReader(Paths.get(fileName), cs)) {
PrintWriter outputStream = new PrintWriter(fileNameOutput);
int lineNum = 0;
String line = null;
while ((line = bReader.readLine()) != null) {
lineNum++;
if (line.split(" ").length > 1) continue;
outputStream.println(line);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

问题出在这里:

if (line.split(" ").length > 1) continue;

每行有1个以上的空格,所以代码:

outputStream.println(line.split(" ")[0]);

永远不会执行,因为 continue 直接跳到下一个 while 迭代所以删除 if (line.split("").length > 1) continue; 检查

编辑在打印消息中添加 line.split("")[0] 以仅获取第一个单词

关于java - 从每一行中获取第一个词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com