2017-04-25 37 views
-2

我創建了下面的Java程序,其中採用了String形式的Statement。該語句的所有單詞都單獨存儲在數組中。如何調用主驅動程序中不存在的方法?

示例 - String statement =「hello world i love dogs」; 獲取存儲在數組中作爲 - {你好,世界,我,愛,狗}

我寫了下面的代碼,但我無法檢查它,因爲當我調用main方法中的方法時,它不會按要求工作。

如何獲得輸出?

public class Apcsa2 { 

/** 
* @param args the command line arguments 
*/ 


public String sentence; 

public List<Integer> getBlankPositions(){ 

    List<Integer> arr = new ArrayList<Integer>(); 

    for (int i = 0; i<sentence.length();i++){ 

     if(sentence.substring(i, i +1).equals(" ")){ 
      arr.add(i); 
     } 


    } 


    return arr; 
} 

public int countWords(){ 
    return getBlankPositions().size() + 1; 

} 

public String[] getWord(){ 

    int numWords = countWords(); 
    List<Integer> arrOfBlanks = getBlankPositions(); 

    String[] arr = new String[numWords]; 

    for (int i = 0; i<numWords; i++){ 

    if (i ==0){ 
    sentence.substring(i, arrOfBlanks.get(i)); 
    arr[i] = sentence; 
    }else{ 

     sentence.substring(i + arrOfBlanks.get(i), arrOfBlanks.get(i+1)); 
     arr[i] = sentence; 

    } 

     } 


    return arr; 

} 



public static void main(String[] args) { 
    // TODO code application logic here 

    int[] arr = {3,4,5,2,4}; 

    String sentence = "hello world I love dogs"; 
} 

}

+0

_I寫了下面的代碼,但我無法檢查它,因爲當我打電話在main方法的方法,它不作爲required._工作。簡單地說,製作所有你想調用'static'的方法,或者在'main'方法內創建一個'Apcsa2'類的實例並調用你想要執行的方法。 –

+0

如果你想「分割」一個字符串,你應該看看'String'類提供的標準功能。你也可以看看這個方法的實際代碼 –

+0

感謝您的快速回復,我寫了以下Apcsa2 p = new Apcsa2(); p.getWord(); System.out.print(p); 還沒有發生。那麼如何輸入句子並獲得所需的輸出? –

回答

0

如果我理解你的目標,我想你想計算單詞的數量,也想打印/檢索。如果是這種情況,那麼你沒有那麼複雜。使用下面的程序。

public class Apcsa2 { 

    public static void main(String[] args) { 
     String input="hello world I love dogs"; 

     String[] arryWords=input.split("\\s+"); 

     //Count-Number of words 
     System.out.println("Count:"+arryWords.length); 

     //Display each word separately 
     for(String word:arryWords){ 
      System.out.println(word); 
     } 

    } 
} 
相關問題