简体   繁体   中英

Repeating a string

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

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

我很快注意到的两件事:您忘记了一个半列,而您对“ repeat”的调用与方法签名不匹配(您忘记了n)

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM