帮助编写一个 void reverse() 方法并使用递归来反转一个完整的句子(Java)
我已经写了一些删除字符串的第一个字符并将其放在剩余子字符串之后然后打印出来的内容,说明是使用递归通过删除句子的第一个字母并将其连接到反转的剩余子字符串来反转句子, IE。 “Hello”产生“olleH”。但我不知道递归部分,任何帮助将不胜感激,谢谢。这是我的代码:
public class Sentence {
private String sentence;
public Sentence(String astring) {
sentence = astring;
}
public void reverse(){
String firstChar = sentence.substring(0,1);
String remainingSen = sentence.substring(1,sentence.length());
System.out.println(remainingSen+firstChar);
}
}
I already wrote something that removes the first character of a string and puts it after the remaining substring and then prints it out, the instructions were to reverse the sentence using recursion by removing the first letter of the sentence and concatenate it to the reversed remaining substring, ie. "Hello" yields "olleH". But i dont know about the recursion part, any help would be appreciated, thanks. This is my code:
public class Sentence {
private String sentence;
public Sentence(String astring) {
sentence = astring;
}
public void reverse(){
String firstChar = sentence.substring(0,1);
String remainingSen = sentence.substring(1,sentence.length());
System.out.println(remainingSen+firstChar);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看到这是一项家庭作业,我将给出一些入门提示:
reverse()
方法采用String
参数并返回字符串的反转版本可以调用自身。如果您弄清楚上面的提示,您应该已经解决了您的问题:-)
Seeing that this is a homework assignment, I'll give some hints to get started:
reverse()
method taking aString
argument and returning the reversed version of the string could call itself.If you work out the hints above, you should have solved your problem :-)
一般来说,如果您想编写递归函数,您将在函数内部调用该函数。例如:
这个例子显然是一个无限循环。
在您的情况下,您希望重复调用反向函数,直到达到定义的状态(其中 Hello 转换为 olleH)。
我认为这是一个家庭作业问题,而且很快就要到期,所以我不会提供确切的答案...
更新 1 :我修改了反向示例以匹配所表达的约束。
Generally, if you want to write a recursive function, you will be calling the function within itself. For example:
This example will obviously be an infinite loop.
In your case, you want to call your reverse function repeatedly until you reach a defined state (where Hello is transformed to olleH).
I assume this is a homework question and it's due soon, so I'm not going to provide an exact answer...
Update 1 : I modified the reverse example to match the constraints that were expressed.
你了解递归的概念吗?如果是这样,请找出基本情况(将停止递归的条件)以及您想要在每个递归步骤中执行的操作。提示:您需要一个递归方法来反转字符串并返回反转后的字符串。不会直接回答硬件问题,但这应该可以帮助您开始。
编辑:(又一个提示)不要尝试使 void reverse() 方法递归。让它调用一个不同的、私有的递归方法来实际执行反转。
Do you understand the concept of recursion? If so, figure out the base case (the condition that would stop the recursion) and what you want to do in each recursive step. Hint: you'll need a recursive method that takes the string to be reversed and returns the reversed string. Not going to straight up answer a HW question, but that should get you started.
EDIT: (One more hint) don't try to make the void reverse() method recursive. Have it call a different, private recursive method that actually does the reversing.