java - Iterate through array for two elements -
i'm trying make quite simple thing. loop through array , 2 elements in 1 iteration instead of one. here code, maybe point mistakes :)
for(int = 0; < temporary.size(); = + 2) { layoutinflater inflater; inflater = (layoutinflater) activity.getparent().getsystemservice(context.layout_inflater_service); view v = inflater.inflate(r.layout.smartuilinear , null); button ls1, ls2; ls1 = (button) v.findviewbyid(r.id.ls1); ls2 = (button) v.findviewbyid(r.id.ls2); ls1.settext("i= "+i+ "info " + temporary.get(i).tostring()); int j = + 1; ls2.settext("i= "+j+ "info " + temporary.get(j).tostring()); linear.addview(v); } edit: problem when size odd number. not wish loose last element. decrementing value if size odd.
well guess question not clear enough. loop works, how not loose last object in list, if list size not even? if list size not on last loop, j shouldn't initialized. hope makes little bit clear
whatever is not working not directly relate loop structure, assuming temporary list number of elements. wrote simplified test program based on code:
import java.util.arraylist; import java.util.arrays; import java.util.list; public class test { public static void main(string args[]) { string[] data = {"aaa","bbb","ccc","ddd"}; list<string> temporary = new arraylist<string>(); temporary.addall(arrays.aslist(data)); (int = 0; < temporary.size(); = + 2) { system.out.println("i= " + + " first " + temporary.get(i).tostring()); int j = + 1; system.out.println("i= " + j + " second " + temporary.get(j).tostring()); } } } it runs, output:
i= 0 first aaa i= 1 second bbb i= 2 first ccc i= 3 second ddd you need @ rest of code, not represented in test program. no clues failure symptoms , definitions of rest of variables not possible diagnose failure.
==============================================================================
following clarification of problem, here variation of test program handles either or odd temporary sizes:
import java.util.arraylist; import java.util.arrays; import java.util.list; public class test { public static void main(string args[]) { system.out.println("odd length"); test(new string[] { "aaa", "bbb", "ccc", "ddd", "eee" }); system.out.println("even length"); test(new string[] { "xxx", "yyy" }); system.out.println("empty"); test(new string[] {}); } private static void test(string[] data) { list<string> temporary = new arraylist<string>(); temporary.addall(arrays.aslist(data)); (int = 0; < temporary.size(); = + 2) { system.out.println("i= " + + " first " + temporary.get(i).tostring()); int j = + 1; if (j < temporary.size()) { system.out .println("i= " + j + " second " + temporary.get(j).tostring()); } } } } output:
odd length i= 0 first aaa i= 1 second bbb i= 2 first ccc i= 3 second ddd i= 4 first eee length i= 0 first xxx i= 1 second yyy empty
Comments
Post a Comment