2

So I need to write a method which accepts one String object and one integer and repeat that string times integer.

For example: repeat("ya",3) need to display "yayaya" I wrote down this code but it prints one under the other. Could you guys help me please?

public class Exercise{

  public static void main(String[] args){

     repeat("ya", 5);
  }

  public static void repeat(String str, int times){

    for(int i = 0;i < times;i++){
        System.out.println(str);
    }
  }
}
2
  • 4
    Change System.out.println to System.out.print (and add a System.out.println(); after your loop). Commented Oct 20, 2016 at 0:28
  • Possible duplicate of Print a String 'X' Times (No Loop) Commented Oct 20, 2016 at 2:59

4 Answers 4

2

You are printing it on new line, so try using this :

public static void repeat(String str, int times){

    for(int i = 0;i < times;i++){
        System.out.print(str);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You're using System.out.println which prints what is contained followed by a new line. You want to change this to:

public class Exercise{
  public static void main(String[] args){
    repeat("ya", 5);
  }

  public static void repeat(String str, int times){
    for(int i = 0; i < times; i++){
      System.out.print(str);
    }
    // This is only if you want a new line after the repeated string prints.
    System.out.print("\n");
  }
}

Comments

1

Change System.out.println() to System.out.print().

Example using println():

System.out.println("hello");// contains \n after the string
System.out.println("hello");

Output:

hello
hello

Example using print():

System.out.print("hello");
System.out.print("hello");

Output:

hellohello

Try to understand the diference.

Your example using recursion/without loop:

public class Repeat {

    StringBuilder builder = new StringBuilder();

    public static void main(String[] args) {    
        Repeat rep = new Repeat();
        rep.repeat("hello", 10);
        System.out.println(rep.builder);    
    }


    public void repeat(String str, int times){
        if(times == 0){
            return;
        }
        builder.append(str);

        repeat(str, --times);
    }

}

Comments

0
public class pgm {

  public static void main(String[] args){

     repeat("ya", 5);
  }

  public static void repeat(String str, int times){

    for(int i = 0;i < times;i++){
        System.out.print(str);
    }
  }
}

1 Comment

Avoid posting code only answers if you can. Tell the OP how your answer answers the question or what was wrong with their provided solution

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.