1. 程式人生 > >哈姆雷特觀後感 一把辛酸淚

哈姆雷特觀後感 一把辛酸淚

lse oid http bsp finall exception fin alt 分享

在我長時間的努力下我終於寫完了那個簡單的任務,我嘗試了好幾種方法後,終於成功了,也是醉了。

為了能同時顯示出現次數最多的字母以及次數,我在出現一次錯誤後改用了相似的兩段程序,我成功了。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Count {
public static void main(String[] args) {

String path = "C:/Users/86173/Desktop/EnglishArtical.txt";
File file = new File(path);
int[] count=new int[26];
int[] count2=new int[26];
for(int i=0;i<26;i++)
{
char a=‘A‘;
int n=((int)a+i);
char des = (char)n;
int count1 = process(file, des);
count[i]=count1;
System.out.println("字符" + des + "在出現" + count[i]+"次");
}
for(int i=0;i<26;i++)
{
char a=‘a‘;
int n=((int)a+i);
char des = (char)n;
int count1 = process(file, des);
count2[i]=count1;
System.out.println("字符" + des + "出現" + count2[i]+"次");
}
int j=0,k=0;
int maxIndex1 = count[0];
int minIndex1 = count[0];
for (int i = 0; i < count.length; i++) {
if(maxIndex1 < count[i]){
maxIndex1 = count[i];
j=i;
}
if(minIndex1 > count[i]){
minIndex1 = count[i];
}
}
int maxIndex2 = count2[0];
int minIndex2 = count2[0];
for (int i = 0; i < count2.length; i++) {
if(maxIndex2 < count2[i]){
maxIndex2 = count2[i];
k=i;
}
if(minIndex2 > count2[i]){
minIndex2 = count2[i];
}
}

if(maxIndex1>maxIndex2)
{ char a=‘A‘;
int n=((int)a+j);
char des = (char)n;
System.out.println("字符" + des + "在出現的次數最多為:" +maxIndex1);
}
else if(maxIndex1<maxIndex2)
{ char a=‘a‘;
int n=((int)a+k);
char des = (char)n;
System.out.println("字符" + des + "在出現的次數最多為:" +maxIndex2);
}


}

public static int process(File file, char c) {
int count = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String temp = "";
while ((temp = br.readLine()) != null) {
char[] des = temp.trim().toCharArray();
for (int i = 0; i < des.length; i++) {
if (des[i] == c){
count++;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
}

技術分享圖片

哈姆雷特觀後感 一把辛酸淚