3 回答
TA贡献1850条经验 获得超11个赞
我认为您想获取实际的字母,并可能检查您是否真的有字母(而不是空白或数字)。
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]);
}
}
}
TA贡献1942条经验 获得超3个赞
创建一个以字符为键,以count(Integer)为值的hashmap。Hashmap存储键值对,其中key是唯一的,put()方法用于将特定的键和值插入hashmap。
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();
}
}
}
TA贡献1806条经验 获得超8个赞
在您的循环中,您只需递增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
}
添加回答
举报