[英]Java recursive method to print one word in a string at a time without loops
For this program, the idea is to print one word in a string at a time using a recursive method, assuming that there is only one word between spaces. 对于此程序,其想法是使用递归方法一次在一个字符串中打印一个单词,假设空格之间只有一个单词。 When I run this program as is, however, it instead prints the string itself.
但是,当我按原样运行此程序时,它将打印字符串本身。
public static void stringByWords(String s) {
if (s.isEmpty())
return;
if (s.indexOf(" ") == 1)
stringByWords(s.substring(s.indexOf(" ") + 1) + "\n");
System.out.println(s);
}//end stringByWords
I realize it would be a hell of a lot easier to do this as an iterative method with just a loop, but I'm required to use recursion as instructed. 我意识到,仅通过循环将其作为迭代方法来进行操作会容易得多,但是我需要按照指示使用递归。 Any tips as to what I'm doing incorrectly will be appreciated.
关于我做错了什么的任何提示将不胜感激。
The trick with recursion is to follow the standard pattern 递归的技巧是遵循标准模式
func(context)
if context is very simple
process context
else
break context into several pieces
call func on each piece
So for your case, the simple situation is a single words with no spaces. 因此,对于您的情况,简单的情况是一个单词没有空格。 Otherwise break into two pieces and call on each piece:
否则,分成两部分,并呼吁每一部分:
void printWords(String str) {
int space = str.indexOf(' ');
if (space == -1) {
System.out.println(str);
} else {
printWords(str.substring(0, space));
printWords(str.substring(space + 1));
}
}
Alright, after fixing up my code from the tips I was given, it seems to function as intended. 好了,从给出的提示中修正了我的代码之后,它似乎可以正常运行。 I will put the fixed code here in case it is helpful to someone else.
我将把固定的代码放在这里,以防对他人有所帮助。 Thanks to those who had helped.
感谢那些帮助过的人。
public static void stringByWords(String s) {
int space = s.indexOf(' ');
if (s.isEmpty()) //error case
return;
if (space == -1) { //base case
System.out.println(s);
}
else {
stringByWords(s.substring(0, space));//recursive steps
stringByWords(s.substring(space + 1));
}//end else
}//end stringByWords
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.