使用递归计算'a'的实例

时间:2013-11-20 03:24:11

标签: java recursion

我有一个家庭作业,用于开始Java来计算单词或短语中“a”的实例。我收到以下错误。

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出>范围:4     at java.lang.String.charAt(String.java:658)     在aHomework.aHomework.countAInWord(aHomework.java:26)     在aHomework.aHomework.main(aHomework.java:13)   Java结果:1

以下是代码:

import java.util.Scanner;

public class aHomework 
{
public static void main( String [] args )
{
    Scanner inputW = new Scanner(System.in);

    String input = inputW.nextLine();
    countAInWord(input, input.length());    
}

public static void countAInWord( String w , int n)
   {

 int aCount = 0;
 if ( n > 0 )
 {
     if (w.charAt(n) == 'a')
     {
         aCount++;
     }
     else
     {
         n = n-1;
         countAInWord(w, n);
     }
 }
 else
     System.out.println("The number of A's is " + aCount);
   }
}

我一直在寻找递归问题,并且学到了很多东西。

但是,我更愿意修改我的代码,而不仅仅是应对别人。

所以,如果有人愿意告诉我为什么会收到上述错误,我会非常感激。

2 个答案:

答案 0 :(得分:0)

您收到错误的原因是因为您将n设置为input.length()。 假设字符串是“halo”,input.length()将返回4。

但是当你使用string.charAt()方法时,字符串索引是从0开始的,这意味着你可以调用的最大值是string.charAt(3),它应该返回'o'。但是因为你用n = 4调用你的递归函数,所以在你的代码中它会调用string.charAt(4),它在该字符串中是OutOfBound。因此你得到了那个错误。 :)

尝试使用input.length() - 1调用递归方法 :d

public static void main( String [] args )
{
    Scanner inputW = new Scanner(System.in);

    String input = inputW.nextLine();
    countAInWord(input, input.length()-1);    
}

其他一些错误:(请参阅我在代码中的评论)

public static void countAInWord( String w , int n)
{

int aCount = 0; // Everytime you enter this recursive function, it will reset to 0, which should not be the case.
if ( n > 0 )
{
     if (w.charAt(n) == 'a')
     {
         aCount++;
         // Yeah you found an 'a', then what? You should call the recursive function again to continue checking. (like how you do it in the else function below)
     }
     else
     {
         n = n-1;
         countAInWord(w, n);
     }
 }
 else
     System.out.println("The number of A's is " + aCount);
   }
}

答案 1 :(得分:0)

回答您的输出问题

变量aCount应该被声明为函数中的一个参数,如countAInWord(String w , int n, int aCount),因此aCount的值可以传递给函数的每次迭代

这是因为函数中声明的变量只能在函数中访问。

在每次调用函数countAInword时,都会声明一个新的aCount,并且对该变量的任何增量仅影响该函数调用中的aCount实例。

再次调用相同的函数时,该值不会传递给该函数调用。而是再次宣布另一个aCount

因此,当您最终打印aCount的值时,您将打印最后一个函数调用的aCount实例。

最后,您应该删除else语句,因为无论在该迭代中是否找到'a',都应该执行其中的代码

希望这有帮助

相关问题