2014-02-08 35 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或字符串只有一个字母时停止的方法吗? –