Paras Keshiv Paras Keshiv - 3 months ago 7
Java Question

Can i use for each in this program instead of for loop ? If yes them please show me how

class MissingArray
{
public static void main(String args[])
{
int found=0;
int[] array1={1,2,3,4,5};
int[] array2={2,3,1,0,5};
for(int i=0;i<array1.length;i++)
{
found=0;
for(int j=0;j<array2.length;j++)
{
if(array1[i]==array2[j])
{
found = 1;
break;
}
}
if(found == 0)
{
System.out.println("Missing Number is = " +array1[i]);
}
}
}
}


Here when I try to do "for each" I get this exception:
ArrayIndexOutOfBoundException
.

Answer

Give this a try:

public static void main(String args[])
{
    int[] array1 = {1, 2, 3, 4, 5};
    int[] array2 = {2, 3, 1, 0, 5};
    for (int num1 : array1)
    {
        boolean found = false;
        for (int num2 : array2)
        {
            if (num1 == num2)
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            System.out.println("Missing number is " + num1);
        }
    }
}