John P. John P. - 1 month ago 7
Java Question

Printing a string of 'n' characters by repeating a string

This is for my revision. I'm trying to build a string of

int n
characters by repeating
String s
. The answer I'm trying to get is

This is what I have so far. When index reaches 4, it would obviously be out or bound as the string has only 4 characters. I want it so that when index reaches 3 it goes back to 0 and continues on until int n satisfies(this might be the wrong word to use) 10. Sorry if the question isn't clear enough.

public static void main(String[] args){

beads("test", 10);


public static void beads(String s, int n){

char[] eachChar = new char[n];
for (int index = 0; index < n; index++) {
eachChar[index] = s.charAt(index);



One simple solution is to modulo the index by the length of the string:

  eachChar[index] = s.charAt(index % s.length());