Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a string using a for loop

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);
like image 392
Rednuam Avatar asked Mar 09 '26 12:03

Rednuam


1 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));
    }
}
like image 65
Arvind Kumar Avinash Avatar answered Mar 12 '26 03:03

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!