简体   繁体   English

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

[英]Writing a non-static method as a static method

I'm trying to write this method as a static method but I don't fully understand how static methods work past them not creating objects to work with. 我正在尝试将此方法编写为静态方法,但是我不完全了解静态方法如何通过它们而不创建对象来使用。

This is the method I'm trying to convert 这是我要转换的方法

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]++;
        }
    }
}

This method just takes a string and records the number of times each letter showed up in the String 该方法只需要一个字符串,并记录每个字母在字符串中出现的次数

Im trying to write this as a static method and I have this method stub 我试图将此写为静态方法,但我有此方法存根

public static LetterCounter buildCounter(String str)
{

}

Since this is a learning exercise, I wouldn't write any code, but describe what needs to be done: 由于这是一项学习练习,因此我不会编写任何代码,而是描述需要完成的工作:

  1. Create a new instance of LetterCounter 创建一个新的LetterCounter实例
  2. Call an instance method process on it, passing str that you got in your buildCounter 在其上调用实例方法process ,传递您在buildCounter获得的str
  3. Return the instance of LetterCounter that you created in step 1. 返回您在步骤1中创建的LetterCounter实例。

You are done! 大功告成!

Your current code would require that counts[] be declared as static also, meaning there is only one counts[], and every time you call MyClass.process("blah") it would increase the class variable counts[index] 您当前的代码将要求counts []也声明为静态,这意味着只有一个counts [],并且每次调用MyClass.process(“ blah”)都会增加类变量counts [index]

I am guessing but I think what you are trying to do is create a static "utility' function to return an array of counts for the various charactors in the passed in string? So something similar to this (untested) code. then you would call something like MyUtilClass.process("xxyz"); In this case "static" means that the process does is not associated with an object, it is more like a "function" or "subroutine" 我正在猜测,但是我想您想做的是创建一个静态的“实用程序”函数来为传入的字符串中的各个字符返回一个计数数组?因此类似于此(未经测试的)代码,那么您将调用类似于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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM