检查扫描的文件是否包含字母表数组中的字母,并计算出现在另一个数组中的次数



我用字母表填充了一个数组,并创建了另一个数组来计算.txt文件中每个字母的出现次数。

lettersLabels数组是String类型,因为我的老师预先制作了一个条形图代码,lettersLabel是String。字母频率加倍也是如此。我的老师还让我们用扫描仪逐行扫描文件。

我需要帮助让代码扫描行,检查每个字母是否都是lettersLabels数组的一部分,然后取该字母值并将其添加到lettersFrequency数组中。

下面我进入if循环,检查字母是否是数组的一部分。我不知道如何将计数器添加到字母的频率数组中。

很抱歉,如果这还不够,我是Java/编码的新手。

// Array for lowercase alphabet with ascii
String[] lettersLabels = new String[26];
for (int i = 0; i < 26; i++) {
lettersLabels[i] = String.valueOf((char)(97 + i));
}
// Creates Array for frequency of letters occurrence 
double[] lettersFrequency = new double[26];

// Scanner for .txt Files
File inputFile = new File(FILE_NAME);
Scanner scan = new Scanner(inputFile);

// While loop to scan file line by line for letters in lettersLabels array, counting occurrences, and adding to lettersFrequency array.
while (scan.hasNext()) {
String readFile = scan.nextLine().toLowerCase();
for (int i = 0; i < readFile.length()-1; i++) {
if (readFile = lettersLabels[i]) { // Don't know if this works
// Need help with adding counter here.
}
}
}

scan.close();
}
}

您可以使用lettersFrequency[letterNumber] += 1;增加频率数组中某个值的计数,但是,您需要按如下方式更正for循环,并进行正确的字符串检查。阅读我下面的注释以查看所做的更改:

//Remove the -1 from this line, otherwise the last letter of your line won't be checked, you already use < instead of <= so the -1 is not necessary
for (int i = 0; i < readFile.length(); i++) {
//Add a new loop to check the 26 possible letters
for (int x = 0; x < 26; x++) {
//Use readFile.charAt(i) to get the current char in the line
//And use .equals(...) to compare the current character to the one in your lettersLabels array
//Note that we need to add +"" after charAt(i) to convert it back to a string
if (lettersLabels[x].equals(readFile.charAt(i)+"")) {
//Finally incriment count by 1 for any matched letters
lettersFrequency[x] += 1;
}    
}
}

您可以直接使用该字符作为索引来增加lettersFrequency中的值。

while (scan.hasNext()) {
String readFile = scan.nextLine().toLowerCase();
for(char c : readFile.toCharArray()) {
if(Character.isAlphabetic(c)) {
int index = c - 97;
//int index = Character.getNumericValue(c)-10;
lettersFrequency[index]++;
}
}
}

或者您可以使用Character.getNumericValue(char(方法。

最新更新