John P. John P. - 1 year ago 51
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);


Answer Source

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

  eachChar[index] = s.charAt(index % s.length());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download