#java
#java
Вопрос:
Я должен написать программу, в которой я должен найти, сколько каждой буквы алфавита находится в файле «test.txt » и разделите это число на общее количество букв, чтобы найти процентное вхождение каждой буквы (чего я еще не сделал). Однако я даже не знаю, как найти номер каждой буквы, присутствующей в текстовом файле. Вот моя крайне неудачная попытка. Кто-нибудь, пожалуйста, может мне помочь.
import java.io.*;
class EnglishAnalysis
{
public static void main(String[] args)
{
try
{
char letters[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
int count = 0;
int totalLetters = 0;
String lineCharacters [];
String line;
line = br.readLine();
while (line != null)
{
lineCharacters = line.split("");
for (int i = 0; i < lineCharacters.length; i )
{
if (!Character.isWhitespace(line.charAt(i)))
totalLetters ;
for (int j = 0; j <= i; j )
{
if (line.charAt(i) == letters[j])
count ;
System.out.println(line.charAt(i) " : " count);
}
}
line = br.readLine();
}
System.out.println(totalLetters);
br.close();
}
catch (IOException e) {}
}
}
Комментарии:
1. Подсказка: каждый символ является целым. С помощью небольшой математики вы можете конвертировать
a
в0
,b
в1
и так далее. Тогда это просто вопрос увеличения значения int в этой позиции в массиве (предполагается, что все буквы в нижнем регистре, как в вашем массиве)2. Подсказка 2: В качестве альтернативы вы могли бы использовать
Map
(но массив является более эффективным решением).3. ваш
count ;
используется глобально для всех символов, вы можете установить количество на карте, как предложил Эллиот.4. Здесь одно из возможных решений.
Ответ №1:
Я применил другой подход. Обратитесь к коду и комментариям к коду ниже для объяснения.
Код:
package main;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
try {
char letters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
double percentage[] = new double[26]; // declare a variable that will hold the percentages of each letter
String path = "sample.txt";
// Read all the contents of the file
String text = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
// make a temporary copy of the content without all the letters
String allLetters = text.replaceAll("[a-z] ", ""); //
// Get the total number of characters in the file
// by subtracting the new length (the length after all the letter has been
// deleted) from the original length
int totalNumOfLetters = text.length() - allLetters.length();
// convert the contents into lower-case
text = text.toLowerCase();
for (int i = 0; i < letters.length; i ) {
char c = letters[i];
// make a temporary copy of the content without the current letter
String tmp = text.replaceAll(c "", "");
// subtract the new length (the length after current letter has been deleted)
// from the original length
int count = text.length() - tmp.length();
// get the percentage of the occurrence of the current letter
percentage[i] = (double) count / (double) totalNumOfLetters * 100.00;
}
DecimalFormat df2 = new DecimalFormat(".##"); // for formatting only
for (int i = 0; i < percentage.length; i ) {
System.out.println(""" letters[i] "" has a percentage of " df2.format(percentage[i]) "%");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Пример файла:
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
Пример вывода:
"a" has a percentage of 5.88%
"b" has a percentage of 5.88%
"c" has a percentage of 5.88%
"d" has a percentage of 5.88%
"e" has a percentage of 5.88%
"f" has a percentage of 5.88%
"g" has a percentage of 5.88%
"h" has a percentage of 5.88%
"i" has a percentage of 2.94%
"j" has a percentage of 2.94%
"k" has a percentage of 2.94%
"l" has a percentage of 2.94%
"m" has a percentage of 2.94%
"n" has a percentage of 2.94%
"o" has a percentage of 2.94%
"p" has a percentage of 2.94%
"q" has a percentage of 2.94%
"r" has a percentage of 2.94%
"s" has a percentage of 2.94%
"t" has a percentage of 2.94%
"u" has a percentage of 2.94%
"v" has a percentage of 2.94%
"w" has a percentage of 2.94%
"x" has a percentage of 2.94%
"y" has a percentage of 2.94%
"z" has a percentage of 2.94%
Ответ №2:
Это работает только в том случае, если слова в этом файле находятся на одной строке, хотя пробелы допустимы. Возможно, я смогу решить эту проблему завтра, если у вас все еще есть проблема, но у меня завтра урок, поэтому я должен идти спать. Надеюсь, это поможет!
import java.io.*;
import java.util.*;
public class CountLettersFromFile {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("test.txt");
BufferedReader br=new BufferedReader(file);
String[] lineCharacters;
String line;
line=br.readLine();
int totalLetters=0;
lineCharacters=line.split("");
for (int i = 0; i < lineCharacters.length; i ) {
if(!Character.isWhitespace(line.charAt(i)))
totalLetters ;
}
double[] count = new double[255];
int length = line.length();
for (int i = 0; i < length; i ) {
count[line.charAt(i)] ;
}
char[] ch = new char[line.length()];
for (int i = 0; i < length; i ) {
ch[i] = line.charAt(i);
int find = 0;
for (int j = 0; j <= i; j ) {
if (line.charAt(i) == ch[j])
find ;
}
if (find == 1 amp;amp; !Character.isWhitespace(line.charAt(i))) {
System.out.printf("Occurance of character "" line.charAt(i) "" is: %.0f %n"
, count[line.charAt(i)]);
System.out.printf("Percent occurance of character "" line.charAt(i) "" is: %.3f %n"
, (count[line.charAt(i)])/totalLetters,"%");
System.out.println("n------------------------------------------------");
}
}
}
}
test.txt файл включает:
салам мен адам мен адам салам
Вывод:
Количество символов «s» равно: 2
Процент встречаемости символа «s» равен: 0.083
Количество символов «a» равно: 8
Процент встречаемости символа «a» равен: 0,333
Количество символов «l» равно: 2
Процент встречаемости символа «l» равен: 0.083
Количество символов «m» равно: 6
Процент появления символа «m» равен: 0,250
Количество символов «e» равно: 2
Процент встречаемости символа «e» равен: 0.083
Количество символов «n» равно: 2
Процент встречаемости символа «n» равен: 0.083
Количество символов «d» равно: 2
Процент появления символа «d» равен: 0.083