I want to write a program that would pass an integer and a string to a value-returning method. I know how to do this part, however I need to concatenate the int (which is 2) and the string (which says "bye"), and have it print the string the number of the int. (Example: Bye Bye).
I will respond clarifying the issue as soon as possible.
You can concatenate String with int in Java like this:
String result = "some " + 2;
The string should go first in this "+" operator.
try this out
private String repeateAndConcateString (int prm_Repeat, String prm_wordToRepeat){
if(prm_Repeat <=0 || prm_wordToRepeat == null){
return "";
}
String temp = "";
for(int i= 1 ; i<=prm_Repeat ; i++){ // loop through the number of times to concatinate.
temp += prm_wordToRepeat; //Concate the String Repeatly 1 to prm_Repeat
}
return temp; // this will return Concatinate String.
}
For string repeat, Apache StringUtils have method repeat .
Or an implementation without externals:
public static String repeat(int n, String s){
StringBuilder sb = new StringBuilder(n * s.length());
while(n--)
sb.append(s);
return sb.toString();
}
Integers can be converted to a string by both references: String.valueOf and Integer.toString . String concatenation works like math addition ( + ).
Try this.
static String repeat(int times, String s) {
return IntStream.range(0, times)
.mapToObj(x -> s)
.collect(Collectors.joining(" "));
}
and
System.out.println(repeat(2, "bye"));
// -> bye bye
public String repeatString(String str, int n)
{
if(n<1 || str==null)
return str;
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++)
{
sb.append(str);
if(i!=(n-1)) // If not the last word then add space
sb.append(" ");
}
return sb.toString();
}
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.