【发布时间】:2014-11-17 14:49:03
【问题描述】:
我已经用两种方法更新了我的代码,而不是以前的方法。但是我仍然卡住了,不知道如何创建和调用将替换 Character.isLetter(s.charAt(i)) 的方法。此方法假设接收一个 char,并返回一个 int 以与 countLetter() 方法一起使用。
方法是:
int [] countLetters (string s), int pos(char x), and void printResults(int[] counts)
是的,int [] countLetters 确实需要返回一个数组。我只是想知道如何让 pos 方法而不是 character.isLetter 工作。
这是我目前得到的:
import java.util.Scanner;
public class CharCount {
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a string: ");
printResults(null);
}
/*
* This method counts the number of occurrences in the inputed
* string and returns the array with the count.
*/
public static int[] countletters(String s){
int[] counts = new int[26];
for(int i = 0; i < s.length(); i++){
if (Character.isLetter(s.charAt(i))){
counts[(int)s.charAt(i) - 'a']++;
}
}
return counts;
}
public static int pos(char x){
return (int)charAt();
}
private static int charAt() {
// TODO Auto-generated method stub
return 0;
}
/*
* This method prints the results of the string count
*/
public static void printResults(int[] counts){
String s = kbd.nextLine();
counts = countletters(s.toLowerCase());
System.out.println("\nLetter frequencies:");
for (int i =0; i < counts.length; i++){
if (counts[i] != 0){
System.out.println((char)('a' + i) + " - " + counts[i] );
}
}
}
}
我觉得我需要从counts[(int)s.charAt(i) - 'a']++ 开始并将其移至打印方法。
谢谢。
【问题讨论】:
-
如果这是我的任务,我会从创建三个方法开始,一开始它们是空的,然后我会尝试开始尝试填充它们中的每一个,一个一次,在我去的时候测试每一个。考虑放弃这个问题,因为它可能被问得太早了,试着自己做,如果仍然卡住,然后再提出一个更具体的问题。
-
请注意,您的问题已声明
countLetters方法返回一个 int 数组。你确定这是正确的,它应该是一个数组吗?第二种方法没有正确声明或无法理解——请澄清一下。 -
你真的应该尝试自己做这件事,而不是让互联网为你做。您已经确定了要提取的一段代码。
-
我更新了我的程序并设法从主程序中分解了第二种方法。我只是不知道要打破什么才能隔离 POS 方法,我很确定它以某种方式使用 if(Character.isLetter(s.charAt(i))){... 但想不出如何开始自己创建它。
标签: java