Kartik Chugh ヅ Kartik Chugh ヅ - 7 months ago 8
Java Question

Adding Strings to List with the number of a certain letter in them increasing

So I have two int's

v
and
w
, a string
q
, and a list
list
.
I need to make it so that
list
adds a string with a duplication of
q
, ranging from
v
through
w
.

For example: v is 2, w is 4, q is "a".
list should be [aa, aaa, aaaa] by the time the program is done.

I have done various programs similar to this, and I felt like this would be easy, and I still think it is but for some reason I am missing something. I have attempted to solve this by doing

for (int j = v; j <= w; j++) {
String s = "";
for (int k = 0; k < j ; k++) {
s+=q;
}
list.add(s);
}


But that just gives a constant number of Qs. Not changing.

Answer

First, prefer StringBuilder to String concatenation (that pollutes the intern cache for one). And you need to begin by looping v times to create your initial String; then append q. Something like

int v = 2;
int w = 4;
String q = "a";
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < v; i++) {
    sb.append(q);
}
for (int j = v; j <= w; j++) {
    list.add(sb.toString());
    sb.append(q);
}
System.out.println(list);

Output is (as requested)

[aa, aaa, aaaa]
Comments