【问题标题】:Is there a more eloquent way of programming this method?有没有更雄辩的方式来编程这种方法?
【发布时间】:2014-10-29 16:31:28
【问题描述】:
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”,但是每当我尝试在方法中引用它时,它不在主方法的范围内。所以我的解决方法是使其成为“公共静态 int”。有更好的方法吗?

【问题讨论】:

  • 你甚至不使用函数numI的返回值。

标签: java object methods


【解决方案1】:

由于您的方法返回int,您只需在main 方法中使用numI 返回的值分配一个int

例如:

int result = numI(testString,testCh);

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

例如(在numI内):

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2021-11-15
      • 2021-01-17
      • 2018-01-20
      • 2021-09-28
      • 2014-11-24
      相关资源
      最近更新 更多