Friday, 15 January 2010

java - Why is this for loop not working as expected? -



java - Why is this for loop not working as expected? -

i have made loop not working expected. please see code:

for (int = 0; < result.size(); i++) { s = s + "k"; (int ii = 0; ii < result.get(0).size(); ii++) { s = s + "\n"; s = s + result.get(i).get(ii)[0]; } }

result.get(i).get(ii)[0] should output string, outputted successfully, problem string s should contain "k" every time before adding 3 strings, should like:

kstring1 string2 string3 kstring1 string2 string3

i getting "k" 1 time before string. know value of i updating because result.get(i) giving results updated i.

explaining result.get(i).get(ii)[0]:

s string, result arraylist< arraylist< string[]>> means contains arraylist< string[]> objects , each object of `arraylist< string[]> string array.

edit: adding output getting:

k united king ["bakery","store","food","establishment"] 0 oven fresh bakery ["bakery","store","food","establishment"] 1 5 star cng pump station ["gas_station","establishment"] 2

there should "k" right after 0, 1 , 2.

your nested loop status appears incorrect,

for (int ii = 0; ii < result.get(0).size(); ii++) {

should be

for (int ii = 0; ii < result.get(i).size(); ii++) {

edit (based on comments , edit, next time - please include short, self contained, right (compilable), example improve help faster)

arraylist<arraylist<string[]>> result = new arraylist<arraylist<string[]>>(); stringbuilder sb = new stringbuilder(); arraylist<string[]> t = new arraylist<string[]>(); t.add(new string[] { "string1" }); t.add(new string[] { "string2" }); t.add(new string[] { "string3" }); result.add(t); result.add(t); (int = 0; < result.size(); i++) { (int ii = 0; ii < result.get(i).size(); ii++) { if (i != 0 || ii != 0) { sb.append("\n"); } if (ii == 0) { sb.append("k"); } sb.append(result.get(i).get(ii)[0]); } } system.out.println(sb.tostring());

output is

kstring1 string2 string3 kstring1 string2 string3

java string for-loop

No comments:

Post a Comment