【问题标题】:Java helper method in recursive function to read string递归函数中用于读取字符串的 Java 辅助方法
【发布时间】:2017-09-04 19:39:29
【问题描述】:

我在仅使用 2 个参数在我已经工作的递归函数中添加辅助方法时遇到问题,当添加第三个(辅助方法)时,我的代码会中断并寻找解决方案。该程序使用扫描仪对字符串进行键盘输入,对字符进行另一个输入,然后输出字母出现的次数。错误发生在第二个 if 语句和两个 return 语句上。在第二次键盘输入后,我得到了错误:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-1

import java.util.Scanner;

public class recursiveString {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String input = sc.nextLine();
        System.out.println("Enter a character to find number of occurences: ");
        char character = sc.next().charAt(0);
        System.out.println(character + " occurred " + count(input, character, input.length() - 1) + " times.");

    }

    public static int count(String str, char a, int high) {

        if (str.length() == high) // set equal to high to stop the recursion from infinitely looping
            return high;
        if (str.charAt(str.length() - 1) != a) // if the character in the string is  not equal to "a" subtract from count(substring)
            return count(str.substring(0, str.length() - 1), a, high - 1);
        else 
            return 1 + count(str.substring(0, str.length() - 1), a, high - 1); 
            // else add +1 to count for each instance of "a" in the string

    }

}

【问题讨论】:

  • 请想一想:如果调用str.length() - 1,空字符串会导致什么结果?然后想想当你停止递归时,很明显,你调用count,即使是空字符串
  • 字符串来自正确的扫描仪并取输入的长度并从中减去 1?我对最后一个程序没有任何问题,就是在我使用第三个参数添加辅助方法时。
  • Pen + paper with a small String aba 应该会告诉你这个问题 - 有时这种老式的调试工作足够快。否则,任何 IDE 都有调试器,这允许通过程序执行
  • 别忘了,看看Java substring 方法的描述和性质。这是最终排他性的
  • @Devin,我添加了一个高有意义的答案。请注意,它只有在 high = input.length() 时才有效,否则检查是部分的。

标签: java recursion


【解决方案1】:

您缺少递归方法的设计:首先,您应该关注一个问题并为基本案例定义它,或者如果有多个案例。

我对这个问题的看法是,基本情况是空字符串(但在此之前,请确保它不是null)或者high 设置为0。

我对@9​​87654323@的理解是你会用它来设置你想检查字符串中有多少字符出现a;随着字符串变大,检查会更直接,将high 字符a 的搜索出现的含义赋予str.substring(0,high),但我试图使其与您的代码相似。

//we'll use high to "tell" the count method how many characters it will consider into the occurrences from the end of the given string
public static int count(String str, char a, int high) {
    //if the string isn't valid or high just tells it to stop, return 0 as there can be no occurrences of a in str
    if(str == null || str.equals("") || high == 0)
      return 0;

    // if the last character in the string is not equal to a, let's just shrink the string
    if (str.charAt(str.length() - 1) != a)
        return count(str.substring(0, str.length() - 1), a, high - 1);

    // otherwise add this 1 occurrence to the ones it will find in the rest of the string
    else 
        return 1 + count(str.substring(0, str.length() - 1), a, high - 1); 
}

main 中的调用将是:

System.out.println(character+ " occurred " + count(input, character, input.length()) + " times.");

【讨论】:

    【解决方案2】:

    这是一个可能的解决方案,可以帮助您避免索引越界:

    public static int count(String str, char a, int high) {
    
        if (str == null || str.length() == 0) {
        // just to be extra safe, if we have an empty string or null 
            return 0;
    
        }
        //changed this end condition - now high describes how many steps we take before returning the answer
        if (high == 0) // to stop the recursion from infinitely looping
            return high;
        if (str.charAt(str.length() - 1) != a) // if the last character in the string is not equal to "a" subtract from count(substring)
            return count(str.substring(0, str.length() - 1), a, high - 1);
        else 
            return 1 + count(str.substring(0, str.length() - 1), a, high - 1); 
            // else add +1 to count for each instance of "a" in the string
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-03
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2020-06-26
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多