Skip to content

Instantly share code, notes, and snippets.

@zhyunk
Created March 3, 2023 13:32
Show Gist options
  • Select an option

  • Save zhyunk/016803c366bc1e5f03e6bcafc9c0e3f8 to your computer and use it in GitHub Desktop.

Select an option

Save zhyunk/016803c366bc1e5f03e6bcafc9c0e3f8 to your computer and use it in GitHub Desktop.
깜짝 과제2 . 파일을 읽어서 그 안에 알파벳 별 출현 빈도의 개수를 구하여 전체 알파벳 중 각각 몇 % 비율로 나오는지 구하는 프로그램을 작성
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/*
* 과제 10 : 깜짝 과제2 . 영어로 작성 된 제19대 대통령 취임사의 영문 문장을 보고 각 영문 알파벳 별 출현 빈도의 개수를 구하여 전체 알파벳 중 몇 % 비율로 나오는지 구하는 프로그램을 작성
*
* 작성자 : 김지현
* 작성일 : 2023-03-03
* */
public class MiniAssignment10 {
public static void main(String[] args) {
FileUtils file = new FileUtils();
String str = file.getLoadText("C:/Users/xh/Desktop/zb/MiniAssignment/src/GgamJjak2.txt");
int[] arrAlphbetCount = new int[26]; // Aa = 0 ~ Zz = 25 ____ 'A' 65 'a' 97
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'z') {
if (str.charAt(i) >= 'a') {
arrAlphbetCount[str.charAt(i) - 'a']++;
} else {
arrAlphbetCount[str.charAt(i) - 'A']++;
}
sum++;
}
}
for (int i = 0; i < arrAlphbetCount.length; i++) {
System.out.println(String.format("%c = %6d개,%8.2f%%", 'A' + i, arrAlphbetCount[i], ((arrAlphbetCount[i] * 1.0f) / sum) * 100));
}
}
static class FileUtils {
// 파일 읽어오는 클래스 (zb 제공)
public String getLoadText(String filePath) {
StringBuilder sb = new StringBuilder();
try {
Path path = Paths.get(filePath);
List<String> lines = Files.readAllLines(path);
for (int i = 0; i < lines.size(); i++) {
if (i > 0) {
sb.append("\n");
}
sb.append(lines.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment