将非静态方法编写为静态方法

时间:2014-09-19 02:11:44

标签: java static

我试图将此方法编写为静态方法,但我并不完全理解静态方法如何通过它们而不是创建要使用的对象。

这是我尝试转换

的方法
public void process(String str)
{
    for (int i=0; i<str.length(); i++){
        char letter = str.charAt(i);
        int index = Character.toLowerCase(letter-'a');
        if (index>=0 && index<26){
            counts[index]++;
        }
    }
}

此方法只接受一个字符串并记录每个字母在字符串

中出现的次数

我试图把它写成一个静态方法,我有这个方法存根

public static LetterCounter buildCounter(String str)
{

}

2 个答案:

答案 0 :(得分:2)

由于这是一个学习练习,我不会编写任何代码,但会描述需要做的事情:

  1. 创建LetterCounter
  2. 的新实例
  3. 在其上调用实例方法process,传递str
  4. 中的buildCounter
  5. 返回您在步骤1中创建的LetterCounter实例。
  6. 你完成了!

答案 1 :(得分:1)

您当前的代码将要求count []也被声明为静态,这意味着只有一个count [],并且每次调用MyClass.process(“blah”)时它都会增加类变量count [index]

我在猜测,但我认为你要做的是创建一个静态“实用程序”函数来返回传入字符串中各种字符的计数数组?所以类似于这个(未经测试的)代码。 然后你会调用类似MyUtilClass.process(“xxyz”)的东西; 在这种情况下,“静态”意味着进程不与对象关联,它更像是“函数”或“子例程”

public static int[] process(String str) {
    int[] counts = new int[25];
    for (int i=0; i<str.length(); i++){
        char letter = str.charAt(i);
        int index = Character.toLowerCase(letter-'a');
        if (index>=0 && index<26){
            counts[index]++;
        }
    }
 return counts;
}