2013-02-05 56 views
-2

我需要計算文件中以字母「A」開頭和結尾的所有單詞。雖然我能夠統計文件中的所有單詞。下面是代碼...用符號計算文件中的單詞

public class task_1 { 

public static int i; 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) throws IOException { 
    Scanner sc = new Scanner (System.in); 
    String name = sc.nextLine(); 
    sc.close(); 
    FileReader fr2 = new FileReader(name); 
    BufferedReader r = new BufferedReader(fr2); 

    String s=r.readLine(); 

    int n=0; 
    while(s!=null) { 
     System.out.println(s); 
     String [] words = s.split(" "); 
     n += words.length; 
     for(String str : words) 
     { 
      if(str.length()==0) n--; 
     } 
     s=r.readLine(); 
    } 
    fr2.close(); 
    System.out.println(n);               
    } 
} 
+3

那麼,你的問題是什麼? –

+0

你有問題嗎? – CloudyMarble

+0

我需要統計文件中以字母「A」開頭和結尾的所有單詞 – Audo

回答

0
while(s != null) { 
    String [] words = s.split(" "); 
    for(String str : words) { 
     if((str.startsWith("a") || str.startsWith("A")) 
       && (str.endsWith("a") || str.endsWith("A"))) { 
      ++n; 
     } 
    } 
    s = r.readLine(); 
} 
+0

...開始並以字母「A」結尾,所以你需要改變|| on && – iMysak

+0

是的我知道,這就是''&&''代表什麼......我只是檢查它是以「A」還是「a」開始,以「A」或「a」結尾'。 –

0

變化,而塊這樣的:

while(s!=null) { 
        System.out.println(s); 
        String [] words = s.split(" "); 
        for(int i=0; i < s.length(); i++) { 
         String current = words[i]; 
         if(current != null && current.startsWith("A") && current.endsWith("A")) { 
          n++; 
         } 
        } 
        s=r.readLine(); 
       } 
0

'你只需要添加此條件:

for(String str : words) 
{ 
    if(str.length()==0){ 
    n--; 
    }else if(str.startWith("A") && str.endsWith("A")){ 
     // increment the variable that counts words starting and ending with "A" 
     // note this is case sensitive, 
     //so it will search for words that starts and ends with "A" (capital) 
    } 
} 
0
public static void main(String[] args) throws Exception { 
    File file = new File("sample.txt"); 
    Scanner sc = new Scanner(new FileInputStream(file)); 
    int count = 0; 
    while (sc.hasNext()) { 
     String s = sc.next(); 
     if (s.toLowerCase().startsWith("a") 
       && s.toLowerCase().endsWith("a")) 
      count++; 
    } 
    System.out.println("Number of words that starts and ends with A or a: " 
      + count); 
} 

如果你想的話O數量總數只是刪除if條件。