2013-12-09 139 views
0

我在讓代碼工作時遇到了一些困難。我的一個任務的要求我從外部文件(基本上是通道/詩)使用此數據:字符串拆分方法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()」檢查了我的行,但我不知道我能做些什麼來解決這個問題。有人可以向我解釋爲什麼發生這種情況,並提供一些方法來解決這個錯誤?謝謝!

回答

0

lengthArray對象上的公共字段,代碼試圖調用它作爲使用()

卸下()長度後的方法:

totalWords+=words.length 
0

陣列properties不應包含括號

totalWords += words.length; 
         ^
0

length是AP陣列的roperty,訪問它不具有()

0

請改變:

totalWords+=words.length(); 

totalWords+=words.length; 
1

答案是陣列的長度由length字段,而不是length給定方法。換句話說,改變

totalWords+=words.length(); 

totalWords+=words.length;