简体   繁体   中英

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(). I checked my line with the "totalWords+=words.length()", but I don't know what I can do to fix the problem. 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. 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 ()

Remove the () after length:

totalWords+=words.length

Array properties shouldn't contain parenthesis

totalWords += words.length;
                          ^

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

please change:

totalWords+=words.length();

to

totalWords+=words.length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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