blockByblock
blockByblock

Reputation: 416

String repeat with method

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);
    }
  }
}

Upvotes: 2

Views: 2480

Answers (4)

Blasanka
Blasanka

Reputation: 22437

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);
    }

}

Upvotes: 1

thetraveller
thetraveller

Reputation: 445

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);
    }
}

Upvotes: 2

Arunachalam
Arunachalam

Reputation: 9

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);
    }
  }
}

Upvotes: 0

Eli Sadoff
Eli Sadoff

Reputation: 7308

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");
  }
}

Upvotes: 2

Related Questions