Reputation: 47
I'm fairly new to programming. I'm trying to repeat the word in a given string the amount of times by a given number in the same string. I have decided to loop through the string and add each char to a new string to print out but I'm getting an out of index error.
final String string = "Hello";
final int num = 3;
int number = string.length() * num;
String str = "";
for (int i = 0; i < number; i++) {
str += string.charAt(i);
}
System.out.println(str);
Upvotes: 3
Views: 1543
Reputation: 78945
You are getting the error because the value of i
is going beyond the last index available in Hello
. The last index in Hello
is "Hello".length() - 1
whereas the value of i
is going beyond this value because of your loop terminating condition:
i < string.length() * num;
By the way, if you want to repeat Hello
3 times, you should do it as
for(int i = 0; i < num; i ++){
System.out.print(string);
}
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
for (int i = 0; i < num; i++) {
System.out.print(string);
}
}
}
String#repeat
With Java 11+, you can do it without using a loop by using String#repeat
:
System.out.println(string.repeat(num));
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
System.out.println(string.repeat(num));
}
}
Upvotes: 3
Reputation: 464
Just keep it simple
String string = "Hello";
int num = 3;
for (int i = 0; i < num; i++) {
System.out.println(string);
}
If you want to have your result in a new String
you can just do this :
String string = "Hello";
int num = 3;
String res = "";
for (int i = 0; i < num; i++) {
res += string;
}
System.out.println(res);
Upvotes: 2
Reputation: 101
Just adding this in here since you stated you're learning. Java has a StringBuilder class, super easy to use
And according this this induvial class using StringBuilder is incredibly more efficient than concatenate.
StringBuilder vs String concatenation in toString() in Java
Upvotes: 1