按符号计算文件中的单词

时间:2013-02-05 10:03:34

标签: java

我需要计算文件中的所有单词,以字母“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);                                                          
    }
}

5 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();
                }

答案 2 :(得分:0)

添加条件以检查for循环中单词的开头字母和结束字母

for(String str:words)         {

        if(str.length()==0) n--;
    }

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#startsWith(java.lang.String)

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#endsWith(java.lang.String)

答案 3 :(得分: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)
    }
}

答案 4 :(得分: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);
}

如果您想要计算单词总数,只需删除if条件。