2014-02-08 36 views
1

我正在處理一個遞歸方法,該方法將返回並在我的主方法中打印一個字符串,該字符串將爲N遞減1。刪除一個字母對於字符串的每個遞歸。直到N變成1或者直到字符串有1個字母。 (N是在命令行上一個INT)遞歸方法打印字符串並遞減1,併爲每個遞歸刪除1個字母

例如,如果我的命令行aruments是:5情​​人

它應該輸出太:

5情人節,4 alentine,3 lentine, 2 intine,1 nt,

到目前爲止,我設法倒計數在命令行參數輸入的數字。我只是不知道如何去刪除字符串中的一個字母? :○

到目前爲止我的代碼:

public static void main(String[] args){ 
     int number = Integer.parseInt(args[0]); 
     String word = new String(""); 
     word = args[1]; 

     String method = recursive.method1(number); 
     System.out.println(method); 
    } 

    public static String method1(int number){ 
     if (number < 0){ 
     return ""; 
     } 
     else{ 
     return number + ", " + method1(number - 1); 
     } 
    } 
+0

你會希望將字符串傳遞給遞歸方法。在'String'類的文檔中查找'substring'。 – Henry

回答

3

您可以通過subString()文檔閱讀,瞭解如何去使用String的部分。

  1. 改變你的方法定義爲包括word
  2. 添加wordreturn聲明:從1st指數
  3. 檢查<=0而不是<0
  4. 原詞的 return number + " " + word +...
  5. 呼叫子

代碼:

public static void main(String[] args){ 
      int number = 5; 
       String word = new String(""); 
       word = "Valentine"; 
       String method = Recurcive.method1(number, word); 
       System.out.println(method); 
      } 

      public static String method1(int number, String word){ 
       if (number <= 0){ 
       return ""; 
       } 
       else{ 
       return number + " " + word + ", " + method1(number - 1, word.substring(1)); 
       } 
      } 

給人,

5 Valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine, 
+0

嗨PopoFibo,不幸的是我得到了一個錯誤使用你的代碼示例與詮釋:10和字符串:十? StringIndexOutOfBOundsException:字符串索引超出範圍:-1。有沒有解決這個錯誤? –

+1

@ Asiax3您的字符串長度需要等於您傳遞的數字,因爲「10」您在3遍中用完整個字符串,並且在第4次它subString()試圖尋找不存在的第4個索引 – PopoFibo

+0

Awh :(你認爲你可以告訴我遞歸方法在數字變爲1或字符串只有一個字母時停止的方法嗎? –