Iterating through an ArrayList
I have several ArrayLists with certain values stored in them and I want to check my program to check the above operators. I have tried looking at the ArrayList api and couldn't find anything that could really do what I wanted.
Ultimately, I'm trying to code something that given user's input, it'll check
X * Y = Z
X / Y = Z
X - Y = Z
X + Y = Z
but the problem is that I'm confused on how to make it check for all the different combinations since the .get() only iterates from 0-max size.
Also, I know that .get() returns an Object, which I have tried to convert to an int and have it do the above but, again, it would only check the combinations when they were all in the same index.
*edit*
I'm also confused on how to iterate through 3 different ArrayLists
Code java:
for (int i = 0; i < list[k1].size(); i++) //this only goes up to k1's ArrayList size
{
int x = Integer.parseInt((String)list[k1].get(i));
if(x + y == z) // y and z are suppose to be like x but with list[k2] and list[k3]
{
count++;
}
}
*edit*
I just tried using the Iterator class but I'd rather use the for loop if I could figure out a way to do the above. The below doesn't work though, it'll loop infinitely with no increasing count. It's just a general idea of what I'm trying to do.
Code java:
Iterator x = list[k1].iterator();
Iterator y = list[k2].iterator();
Iterator z = list[k3].iterator();
int count = 0;
int r = Integer.parseInt((String)x.next());
int s = Integer.parseInt((String)y.next());
int t = Integer.parseInt((String)z.next());
while(x.hasNext() && y.hasNext() && z.hasNext())
{
if(r + s == t)
{
count++;
}
if(r - s == t)
{
count++;
}
if(r * s == t)
{
count++;
}
if(r / s == t)
{
count++;
}
}
Re: Iterating through an ArrayList
Hi,
I would like to ask you to use Array List of Integer type so the declaration will be
as follow:
List<Integer> list= new ArrayList<Integer>();
Then iterate it using java 5 for loop like below:
for(Integer integerObj: list){
//place your logic here.
}
bean factory
Re: Iterating through an ArrayList
Quote:
Originally Posted by
abani
Hi,
I would like to ask you to use Array List of Integer type so the declaration will be
as follow:
List<Integer> list= new ArrayList<Integer>();
Then iterate it using java 5 for loop like below:
for(Integer integerObj: list){
//place your logic here.
}
Thanks for the response. I'm not sure how to implement this sort of thing yet though. I did figure out how to do what I wanted though. It was rather simplistic and I'm kicking myself over it. Basically I had to use a nested for loop and it was easily solved. Thanks again for the input!