如何在java中的main方法中测试另一个方法

时间:2012-11-08 00:24:03

标签: java count

我正在练习测试我的主要功能中的方法(它是计算元音的数量)。 我想知道如何在这里实现我的代码?我的代码中是否也有缺陷?

public class MethodPractice{

    public static void main(String[] args){

        numVowels(howcanitesthere);    //i know this is wrong, just trying smth..

    }

    public static int numVowels(String s){

        String text = ("");
        int count = 0;

        for(int i = 0; i < text.length() ;i ++){
            char c = text.charAt(i);

            if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
                count++;
            }
        }
        System.out.println(count);

    }
}

3 个答案:

答案 0 :(得分:1)

有几种方法:

  • 您可以从命令行或
  • 传递参​​数
  • 您可以传递一堆硬编码的参数,并检查答案。

以下是一个例子:

命令行参数:

if (args.length == 1) {
    System.out.println(numVowels(args[0]));
}

硬编码字符串:

if (numVowels("hello") == 2) {
    System.out.println("OK");
} else {
    System.out.println("wrong");
}

答案 1 :(得分:1)

System.out.println(numVowels("A test string"));

答案 2 :(得分:0)

numVowels("test string");

......就是这样!

但是您必须在功能中将System.out.println(count);更改为return count;才能使其正常工作。否则你会收到错误。

执行此操作后,请尝试将其放入主方法中:

System.out.println(numVowels("test string"));