Cannot find symbol while using .repeat() method in Java (The code is working in Netbeans)

Viewed 2787

I'm solving a problem in Java and it works perfectly in Netbeans without any error message but the website's compiler where I upload my code drops me the following error:

Compile error:  Main.java:16: error: cannot find symbol
            String finalString = newString.repeat(n + 1);
                                          ^
  symbol:   method repeat(int)
  location: variable newString of type String

My code:

Scanner sc = new Scanner(System.in);

        String myString = sc.nextLine();
        int n = sc.nextInt();
        String finalString = "";

        for (int i = 0; i < myString.length(); i++) {
            String newString = myString.substring(n + 1, myString.length());

            finalString = newString.repeat(n + 1);

        }
        System.out.println(finalString);
    }
}

Sample input:
Hello
2

Sample output:
lololo

2 Answers

String.repeat was added in Java 11. Presumably, the website you're uploading to uses an older JDK.

If you cannot modify/upgrade the JDK there, you could implement the same logic yourself, e.g., by using Collections.nCopies and then streaming and joining them:

finalString = Collections.nCopies(n + 1, newString).stream().join(Collectors.joining(""));

String.repeat has been included since Java 11 version. Maybe the website you're using has a JDK version below 11.

Use you can always use this code for the String repetition:

String s = "Hello";
System.out.println(Collections.nCopies(3,s));

For further proceedings, I suggest you update your project JDK to the latest one in your respective IDE.

Related