有没有更有说服力的方法编程这种方法?

时间:2014-10-29 16:31:28

标签: java object methods

import java.util.Scanner;

public class MethodWalkthrough {
    private static int num = 0;
    public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);
        boolean stringHasI = true;

        while(stringHasI){
            String testString = kb.next();   //String to test
            char testCh = kb.next().charAt(0);   //char to determine how many instances it appears in testString
            numI(testString,testCh);
            if(num==0)
                stringHasI = false;
            num=0;

        }

    }

    public static int numI(String test, char testChar){

        for(int i = 0;i<test.length();i++){
            if(test.charAt(i)==testChar)
                num++;
        }
        System.out.println("There are "+num+" "+testChar+"'s in "+test);
        return num;

    }
}

我想实际使用返回的值“num”,但是当我在方法中尝试引用它时,它不在main方法的范围内。所以我的解决方法是使它成为“公共静态int”。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

由于您的方法返回int,因此您只需在int方法中为main指定numI返回的值即可。

例如:

int result = numI(testString,testCh);

这意味着从您的类中删除static int num声明,并在int方法范围内初始化并返回numI

例如(在numI内):

int result = 0;
for(int i = 0;i<test.length();i++){
...
// TODO assign/increment/print "result" instead of former "num"
return result;

答案 1 :(得分:0)

num全局声明是无用的,numI方法可以改进,这是一个紧凑的例子:

public static int numI(String test, char testChar)
{
    int num = 0;
    for (int i = 0; (i = test.indexOf(testChar, i) + 1) != 0; num++);
    return num;
}

用法:

while(stringHasI)
{
    String testString = kb.next();   //String to test
    char testCh = kb.next().charAt(0);   //char to determine how many instances it appears in testString
    int num = numI(testString,testCh);
    stringHasI = num != 0;
}