-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);                                                          
    }
}
4

5 回答 5

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();
}
于 2013-02-05T10:09:21.023 回答
0

更改 while 块:

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();
                }
于 2013-02-05T10:09:45.577 回答
0

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

for(字符串str:单词){

        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)

于 2013-02-05T10:10:52.613 回答
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)
    }
}
于 2013-02-05T10:11:16.280 回答
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条件即可。

于 2013-02-05T10:25:49.900 回答