我很新的Java和我和我的第一项任务挣扎。分配是在一个文本文件(para1.txt)扫描,并通过它来读取并计算每个字母出现了多少次。 (所以,它应该输出像A-57,B-21,C-12等),我觉得我非常接近的答案,不过,我有一个小麻烦实际上是计数的人物,因为他们出现。目前,我的代码打印出“17”为所有的字母,因为有17线在para1.txt文件。这是我到目前为止的代码:
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]);
}
}
}
我想你想采取实际的信件,也许检查,如果你确实有一个字母(而不是空白或数字)。
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]);
}
}
}
在你的循环,你只是递增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
}
创建角色的关键一个HashMap和计数(整数)作为value.Hashmap保存键 - 值对,其中关键是独特的和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();
}
}
}
也许你不应该知道的地图却是一个简单的解决办法是使用一个。
像这样的事情
HashMap<Character, Integer> chars = new HashMap<>();
for(int i = 0; i < characters.length; i++){
if(chars.get(characters[i]) == null){
chars.put(characters[i], 1);
} else {
int num = chars.get(characters[i]);
chars.put(characters[i], num+1);
}
}
for(Character c : chars.keyset()){
print(c + " :" + chars.get(c));
}
可能有一些语法错误,写在这里