Repeating a string using a for loop

Viewed 295

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);
3 Answers

Zero-based index

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

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