用java编写一个程序并取名test.c,统计该文件中出现"if" , "while","for"的次数。
时间: 2023-05-18 15:07:24 浏览: 147
非常感谢您的问题!以下是用Java编写的程序,可以统计test.c文件中出现"if","while","for"的次数:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
String fileName = "test.c";
int ifCount = 0;
int whileCount = 0;
int forCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
ifCount += countOccurrences(line, "if");
whileCount += countOccurrences(line, "while");
forCount += countOccurrences(line, "for");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("if count: " + ifCount);
System.out.println("while count: " + whileCount);
System.out.println("for count: " + forCount);
}
private static int countOccurrences(String line, String word) {
int count = 0;
int index = 0;
while ((index = line.indexOf(word, index)) != -1) {
count++;
index += word.length();
}
return count;
}
}
```
希望这个程序能够帮到您!
阅读全文