2012-11-08 114 views
1

我正在練習在我的主函數中測試我的方法(它是計算元音的數量)。 我想知道如何在這裏實現我的代碼?我的代碼中是否也存在缺陷?如何在我的主要方法中測試另一種方法java

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

    } 
} 
+2

你可以..它傳遞一個字符串?我不明白你在掙扎着什麼。 – Eric

+2

我不知道你真的要求我們幫忙。你想要什麼輸入和這個測試的結果是? – millimoose

+0

歡迎來到StackOverflow!你可以設置你的問題的格式,以便代碼更易讀;請參考[Markdown幫助頁面](http://stackoverflow.com/editing-help)或[編輯問題時提供的格式參考](http://codinghorror.typepad.com/.a/6a0120a85dcdae970b0120a86e29f4970b- PI)。 –

回答

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
System.out.println(numVowels("A test string")); 
+0

也需要返回該值的方法,並使用給定的參數... – jlordo

0
numVowels("test string"); 

......這一切!

但是您必須在您的函數中將System.out.println(count);更改爲return count;才能正常工作。否則,你會得到一個錯誤。

一旦你做到這一點,嘗試把這個在您的主要方法:

System.out.println(numVowels("test string")); 
相關問題