简体   繁体   English

字符串拆分方法Java

[英]String split method java

I'm having a bit of difficulty getting my code to work. 使我的代码正常工作有点困难。 One of my assignments requires me to use this data from an external file (basically a passage/poem): 我的一项任务要求我使用外部文件(基本上是段落/诗歌)中的以下数据:

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

We are trying to find the total number of words, the number of words that have only three letters, and the percentage of occurrence of the three words. 我们正在尝试查找单词总数,仅包含三个字母的单词数量以及这三个单词的出现百分比。 I think I can handle the assignment, but something went wrong in my code while I was working it out: 我认为我可以处理分配任务,但是在我编写代码时代码出了点问题:

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

When I tried to compile to test the code at the moment to see if everything I had done was working properly, I was given an error that said it can't find symbol method length(). 当我现在尝试编译以测试代码以查看我所做的一切是否正常工作时,出现一个错误,提示它找不到符号方法length()。 I checked my line with the "totalWords+=words.length()", but I don't know what I can do to fix the problem. 我用“ totalWords + = words.length()”检查了一行,但是我不知道该如何解决该问题。 Could someone please explain to me why this happened and provide some direction on how to fix this error? 有人可以向我解释为什么会发生这种情况,并就如何解决此错误提供一些指导吗? Thanks! 谢谢!

The answer is that the length of an array is given by the length field, not the length method. 答案是数组的长度是由length字段而不是length方法给出的。 In other words, change 换句话说,改变

totalWords+=words.length();

to

totalWords+=words.length;

length is a public field on an Array object, the code is attempting to invoke it as a method using () lengthArray对象上的公共字段,代码正尝试使用()作为方法来调用它

Remove the () after length: 删除长度后的()

totalWords+=words.length

Array properties shouldn't contain parenthesis 数组properties不应包含括号

totalWords += words.length;
                          ^

length是数组的属性,不带()访问

please change: 请更换:

totalWords+=words.length();

to

totalWords+=words.length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM