3
public static String repeater(int x, String word) {
   if (x > 0) {
       System.out.print(word.charAt(0));
   }

   if (x == 0) {
       return "";
   } else {
       return repeater(number-1, x);
   }

This code gives me the output I want which is basically taking the first letter of a String and printing it 'x' number of times:

Example:

when my 
String = Hello 
and x = 6

HHHHHH

My problem is I want this method to work the same way but without the use of the 'System.out.print()' line. Am I going to have to add a second String? If not, what approach should I take?

2 Answers 2

3

Ok, I see you need it's recursive.

public static String repeater(int x, String word) {
    if (x == 0) {
        return "";
    } else {
        return word.charAt(0) + repeater(x - 1, word);
    }
}

How is this?

For understanding this recursion, it is working like nested parentheses of Mathematics.

"H" + ("H" + ("H" + ("H" + ("H" + ("H" + (""))))))
Sign up to request clarification or add additional context in comments.

4 Comments

It has to be recursion unfortunately
I appreciate you trying to help me though! :)
This is exactly what I was wanting to do. Perfect! Thanks hata !!
This is out of topic but I just wanted to say that this community is just incredible. You guys are out of this world, keep it up :)
0

Yes, you can add second string. And instead of "System.out.print" you can assign value of word.charAt(0) to that variable.

pseudo code-

String output="";

below line of code within repeater method

output=output+convert.tostring(word.charAt(0))

i.e.:

String output="";
public static void repeater(int x, String word) {
  if (x > 0) {
    output += convert.toString(word.charAt(0));
 }

 if (x == 0) {
   return;
 } else {
   repeater(number-1, x);
 }
}

1 Comment

I'm a bit lost as to what you mean. Could you show me instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.