2013-02-05 33 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条件。