【发布时间】:2015-04-25 00:24:46
【问题描述】:
所以对于这个程序,我们将使用递归。我们必须导入一个包含五个单词的文本文件,然后对于这些单词,我们必须找到所有可能的子字符串并将它们存储在一个数组列表中。所以,如果这个词是卡片:cards card car ca cards ard ar a rds rd r ds d s.
说明我们必须创建一个静态方法,该方法返回一个 String 类型的 ArrayList,它只接受一个参数,一个 String。
因此,为了使某些东西递归,它必须调用自身以简化事情,并且必须有一个基本情况的动作。所以现在我有:
public static ArrayList<String> SubstringCalculator (String theName)
{
/* Do I call create a new ArrayList here? Wouldn't that mean
* that every time I call this method an entire new ArrayList
* is created? I only want one ArrayList.
*/
ArrayList<String> result = new ArrayList<String>();
System.out.print (theString);
result.add(theString) // Add the string to the ArrayList
if (theString.length > 1) {
// Make a new string with 1 char less than the original.
String newString = theString.substring(0, theString.length() - 1);
// Call the method again with the new string.
SubstringCalculator (newString);
return result;
}
return theString; // Return the string if it is of length 1.
}
我知道这是不对的,但我不知道该怎么做。有什么帮助吗?
【问题讨论】:
-
和this guy学习同一门课程?
-
看起来像一个类似的问题,虽然我的方向似乎不同。我们被允许在这个上使用循环(据我所知)。
-
theName 是 theString ???输入错误???
-
是的,它应该读取 theName,我的输入错误。
标签: java string recursion arraylist substring