Question

I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:

public static void main(String[] args) {
    // **METHOD** //
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string");
    String str = in.nextLine();

    System.out.println(repeat (str));//Having trouble with this line
}

    // **TEST PROGRAM**//
public static String repeat(String str, int n)
{
    if (n <= 0)
    {
        return ""//Having trouble with this line
    }

    else if (n % 2 == 0)
    {
        return repeat(str+str, n/2);
    }

    else
    {
        return str + repeat(str+str, n/2);
    }
}                
}

I made some changes to my code, but it still is not working

 public static void main(String[] args) {
    // **METHOD** //
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string");
    String str = in.nextLine();
    int n = in.nextInt();

    System.out.println(repeat(str,n));
}

    // **TEST PROGRAM**//
public static String repeat(String str, int n)
{
    if (n <= 0)
    {
        return "";
    }

    else if (n % 2 == 0)
    {
        return repeat(str+str, n/2);
    }

    else
    {
        return str + repeat(str+str, n/2);
    }
}                
}

No correct solution

OTHER TIPS

You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""

Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:

public static String repeat(String str, int n)

As a further note, an easier function might be

    public static String repeat(String str, int n)
    {
        if (n == 0) return "";

        String return_str = "";
        for (int i = 0; i < n; i++)
        {
            return_str += str;
        }

        return return_str;
    }
public static String repeat(String toRepeat, int n){
 if(n==0){
     return "";
 }

 return toRepeat+repeat(toRepeat,n-1);
 }

2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)

You are not passing correct arguments while you calling the desired method.

Call as repeat (str,k) k - should be an integer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top