I'm a beginner with java and one concept is rather unclear to me. I need to create a method that creates a new string by replicating another string. For example, if the String1 is "java" and it is specified that it needs to be repeated 4 times and each of them needs to be separated with a comma, the new string would look like this: java, java, java, java
However, the method should not print it, but only create a new string that is then printed in the main program. This is a problem for me, because I have trouble understanding, how can I use a loop to create something without printing it. I think that the following code would print it correctly:
public static void replicate(String str, int times) {
for (int i = 0; i < times; i++) {
System.out.print(str);
if (i < times -1) {
System.out.print(", ");
}
}
}
How could I transform it so that I could use the method to create a new string without printing it? I am assuming this is something super simple, but I just don't know at all how to do this, because every guide just uses examples of printing in these kinds of situations.
This is much better with Collections and join
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String newstr=String.join(",", Collections.nCopies(3, "java"));
System.out.println(newstr);
}
}
Working fiddle-https://repl.it/repls/OfficialInvolvedObject
The following code should be useful for academic purposes in which you cannot use all of Java's libraries. You want to use a variable to store the repeated text and then return that variable to the main method for it to be printed. For non academic purposes or in cases when efficiency is a priority the java.lang.StringBuilder object should be used.
public static String replicate(String str, int times) {
String newString = "";
for (int i = 0; i < times; i++) {
newString = newString + str;
if(i<times-1){
newString = newString + ", ";
}
}
return newString;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With