please help me with this. i want to scan array1 through elements of array2 and disregard the elements of array2 if it’s found in array1. so a list of fruits will only be left. but the output shows : ball, pencil. where i would want it to display only the elements in fruits. thanks for your help
import java.util.*;
public class CountFruits
{
public static void main(String args[])throws Exception
{
String array1[] = {"apple", "mango", "orange", "banana", "ball", "pencil"};
String array2[] = {"ball", "pencil"};
List<String> fruits = new ArrayList<String>();
for(int x = 0; x < array1.length; x++)
{
for(int y = 0; y < array2.length; y++)
{
if(array1[x].equals(array2[y]))
{
System.out.println(array1[x] + "\t" + array2[y]);
if(!fruits.contains(array1[x]))
{
fruits.add(array1[x]);
}
}
}//end for
}//end for
System.out.println("fruits: " +fruits);
}
}
The if statement if(array1[x].equals(array2[y])) will only be true for ball and pencil, so the fruit array will only add ball and pencil.
You could set the fruit array to hold all of array1 and then, if your if statement is true, remove that element from fruit the array.
or, you could set a boolean isFruit = true (in the outer for loop).
Then, if your if statement if(array1[x].equals(array2[y])) passes, set isFruit to false.
After the iteration of the inner loop, if isFruit is true, add it to the fruit array.