题目描述:
统计文件poem.txt中”春、天、水、花”四个字符出现的次数。
代码:
import java.io.*;
import java.util.Arrays;
public class StringTest{
public static void main(String[] args)throws IOException{
String content = readFile(“poem.txt”); //这里只用相对路径,也可用绝对路径“H:\\…”
int count1 = 0,count2 = 0,count3 = 0, count4 = 0;
for(int i=0;i
if(content.charAt(i) == ‘春’){
count1++;
}
if(content.charAt(i) == ‘天’){
count2++;
}
if(content.charAt(i) == ‘水’){
count3++;
}
if(content.charAt(i) == ‘花’){
count4++;
}
}
System.out.println(““春”出现次数为 ” + count1);
//System.out.println(“\n”);
System.out.println(““天”出现次数为 ” + count2);
System.out.println(“\n”);
System.out.println(““水”出现次数为 ” + count3);
System.out.println(“\r\n”);
System.out.println(““花”出现次数为 ” + count4);
}
static String readFile(String fileName) throws IOException{
StringBuilder sb = new StringBuilder(“”);
String s1=””;
int c1;
FileInputStream f1= new FileInputStream(fileName);
InputStreamReader in = new InputStreamReader(f1, “UTF-8”);
while ((c1 = in.read()) != -1) {
sb.append((char) c1);
}
return sb.toString();
}
}
运行截图:
附带一个知识点:java中System.out.println是输出完之后自动换行的,如果想要取消自动换行,则用System.out.print,输出空行用System.out.println(“\r\n”),其实因为println已经会自动换行,所以直接println(“”)就足够了.