gpt4 book ai didi

递归函数中读取字符串的Java辅助方法

转载 作者:行者123 更新时间:2023-11-29 04:26:29 24 4
gpt4 key购买 nike

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

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -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

}

}

最佳答案

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

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

我对 high 的理解是,您将使用它来设置要检查字符 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.");

关于递归函数中读取字符串的Java辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com