我对Java还是很陌生,我正为第一次工作而苦苦挣扎。任务是扫描一个文本文件(para1.txt),并仔细阅读并计算每个字母出现的次数。 (因此,它应该输出a-57,b-21,c-12等) 我觉得我已经很接近答案了,但是,我很难计算一下出现的字符。目前,我的代码为所有字母打印“ 17”,因为para1.txt文件中有17行。 到目前为止,这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
for (int i = 0; i < 26; i++) {
count[i]++;
}
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
答案 0 :(得分:1)
在循环中,您只需递增count
数组的每个索引:
for (int i = 0; i < 26; i++) {
count[i]++;
}
相反,您可以做的是遍历characters
数组,并在char-'a'
处增加索引,以获得正确的索引:
for(char c : characters) {
count[c - 'a']++;
}
唯一的问题是,如果有任何非字母字符,这将使索引超出范围错误。您可能要确保它在范围内:
int index = c - 'a';
if(index > 25 || index < 0) {
System.out.println("Invalid character");
} else {
//process like normal
}
答案 1 :(得分:1)
我认为您想获取实际的字母,也许要检查您是否确实有字母(而不是空格或数字)。
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
/// change here!
for (int i = 0; i< characters.length ; i++) {
if((characters[i] >='a') && (characters[i]<='z')) {
count[characters[i] -'a' ]++;
}
}
/// change ends.
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
答案 2 :(得分:0)
也许你不应该知道的地图却是一个简单的解决办法是使用一个。
类似这样的东西
DispatchMessage
可能会出现一些语法错误,请在此处写出
答案 3 :(得分:0)
创建一个以字符为键并以count(Integer)为值的哈希图。哈希图存储键值对,其中键是唯一的, put()方法用于将特定的键和值插入哈希表。
public class CharCount {
public static void main(String[] args) {
File f1 = new File("file-path");
HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
try {
Scanner in = new Scanner(f1);
while(in.hasNext()) {
String inputString = in.nextLine();
inputString = inputString.replace(" ", "");
char[] strArray = inputString.toCharArray();
for (char c : strArray) {
if (charMap.containsKey(c)) {
// If character is present in charMap, incrementing it's count by 1
charMap.put(c, charMap.get(c) + 1);
} else {
// If char is not present in charMap ,
// putting this character to charMap with 1 as it's value
charMap.put(c, 1);
}
}
}
// Printing the charMap
System.out.println(charMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}