for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
我的函数没有将counter2
检测为变量,因为它位于嵌套的for循环中。那么我该如何摆脱这种困境呢?
我正在尝试使用参数输入(分别为字符串)并使用ascii表作为参考发布出现次数,正如您所看到的,阻止我完成此操作只有一个障碍。
有什么想法吗?
答案 0 :(得分:0)
您的主要问题是您错过了一个重要事实 - 在您的循环完成之后,您的计数才会完成。
因此,您需要在第一个循环完成后在单独的循环中打印出您的计数。
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}