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);
    }
  }
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
blockByblock
  • 366
  • 2
  • 4
  • 14
  • 4
    Change `System.out.println` to `System.out.print` (and add a `System.out.println();` after your loop). – Elliott Frisch Oct 20 '16 at 00:28
  • Possible duplicate of [Print a String 'X' Times (No Loop)](http://stackoverflow.com/questions/19455473/print-a-string-x-times-no-loop) – smac89 Oct 20 '16 at 02:59

4 Answers4

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");
  }
}
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
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);
    }
}
smac89
  • 39,374
  • 15
  • 132
  • 179
thetraveller
  • 445
  • 3
  • 10
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);
    }

}
Blasanka
  • 21,001
  • 12
  • 102
  • 104
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);
    }
  }
}
smac89
  • 39,374
  • 15
  • 132
  • 179
  • 3
    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 – smac89 Oct 20 '16 at 02:56