In java, how do I increase the index of two array(list)s of different sizes at the same time?
I have two ArrayLists in java that have different sizes. ArrayLists 'probs' and 'theDoubles' (sizes 4 and 5 respectively). Array 'dprobs' (Double[5]) is just an Array that copies the values of 'theDoubles'.
Only those items that do not have zero-length (see '.size() > 0') are allowed to be added. One of them is zero-length, and gets replaced by a '0.0' double (added to the 'theDoubles' ArrayList).
My problem is that I do not know how to get this desired output:
i=1 j=0
i=2 j=1
i=3 j=2
i=4 j=3
j=4
I get this instead:
i=1 j=1
i=2 j=2
i=3 j=3
i=4 j=4
Here is my code:
for (int i = 0; i < 5; i++) {
if (probs.get(i).size() > 0) {
开发者_StackOverflow中文版 System.out.println("i: " + i);
System.out.println("j: " + j);
theDoubles.add(Double.parseDouble(probs.get(i).get(0).getValue()));
dprobs[j] = theDoubles.get(j);
} else {
theDoubles.add(0.0);
}
j++;
}
return dprobs;
I need to display this ('probs' ArrayList contents):
0.0
0.0049522
0.0020487
0.0013568
0.0015332
and I am only getting this:
0.0049522
0.0020487
0.0013568
0.0015332
because 'j' starts at '1' (it ignores the first item, which is '0.0' at index 0).
Any ideas?
Thanks
It is hard to see the full picture because nothing shows where you print the second set of outputs and desired outputs. therefore i will try based on the first set that you posted: you need to increase j only when you are at an i which points to an element that is not zero length. therefore, move the j++ to your "if" block too. it becomes like this:
for (int i = 0; i < 5; i++) {
if (probs.get(i).size() > 0) {
System.out.println("i: " + i);
System.out.println("j: " + j);
theDoubles.add(Double.parseDouble(probs.get(i).get(0).getValue()));
dprobs[j] = theDoubles.get(j);
j++;
} else {
theDoubles.add(0.0);
}
}
return dprobs;
精彩评论