簡體   English   中英

字符串拆分方法Java

[英]String split method java

使我的代碼正常工作有點困難。 我的一項任務要求我使用外部文件(基本上是段落/詩歌)中的以下數據:

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;

lengthArray對象上的公共字段,代碼正嘗試使用()作為方法來調用它

刪除長度后的()

totalWords+=words.length

數組properties不應包含括號

totalWords += words.length;
                          ^

length是數組的屬性,不帶()訪問

請更換:

totalWords+=words.length();

totalWords+=words.length;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM