gpt4 book ai didi

java - java字符串分割方法

转载 作者:行者123 更新时间:2023-12-01 13:43:56 25 4
gpt4 key购买 nike

我在让我的代码运行时遇到了一些困难。我的一项作业要求我使用外部文件中的数据(基本上是一段段落/诗歌):

Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful

我们正在尝试查找单词总数、仅包含三个字母的单词数量以及这三个单词出现的百分比。我认为我可以处理该作业,但在我解决问题时我的代码出了问题:

import java.io.*;
import java.util.*;
public class Prog739h
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\Java programs\\Prog739h\\Prog739h.in"));
int totalWords = 0;
while(kbReader.hasNextLine())
{
String data = kbReader.nextLine();
String[] words = data.split(" ");
totalWords+=words.length();
System.out.println(totalWords);
}
}
}

当我尝试编译以测试代码以查看我所做的一切是否正常工作时,我收到一个错误,指出它找不到符号方法 length()。我用“totalWords+=words.length()”检查了我的行,但我不知道我能做些什么来解决这个问题。有人可以向我解释为什么会发生这种情况并提供一些有关如何修复此错误的指导吗?谢谢!

最佳答案

答案是数组的长度是由 length 字段给出的,而不是由 length 方法给出的。换句话说,改变

totalWords+=words.length();

totalWords+=words.length;

关于java - java字符串分割方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20479957/

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