How to print statement outside loop to avoid duplicates?

I would like my print statement to be outside the loop so the statement doesn’t print the same thing over and over. The for loop below simply checks a number from one array against another to find out how many matches have been found. Defining the variables above and printing the statements below results in a “variable not initialised error” which is understandable.

for (int i = 0; i < 6; i++)
{
    int chkNum = myArray[i];
    int lottMtch = count(chkNum, rndNum);

    if (lottMtch > 0)
    {
        System.out.println(lottMtch + "matches found");
        System.out.print(chkNum);
    }
    else {
        System.out.print("no matches found");
    }
}

Answer

this would not really make sense .. if you want than Try this …

        int lottMtch[]=new int[myArray.length];
           Arrays.fill(lottMtch, 0);
            for (int i = 0; i < 6; i++)
            {
                int chkNum = myArray[i];
               lottMtch[i] = count(chkNum, rndNum);

            }
            for (int i = 0; i < 6; i++)
            {
                       if (lottMtch[i] > 0)  
                            System.out.println(lottMtch[i] + " matches found "+ myArray[i]);
            }

If you wan to found just how many match of rndNum in myArray Than try this

Here i assume rndNm is global

        int lottMtch=0;

            for (int i = 0; i < 6; i++)
            {

               lottMtch += count(myArray[i], rndNum);

            }

                       if (lottMtch> 0)  
                            System.out.println(lottMtch + " matches found "+ rndNum);

As per discussed in comment Try this ..

Map<Integer,Integer> map = new HashMap<Integer,Integer>();


       for (int i = 0; i < 6; i++)
         {
             Integer chkNum = myArray[i];
            Integer cnt = (Integer)count(myArray[i], rndNum);
              if(cnt>0)
              {
                  if(map.get(chkNum)==null)
                     map.put(chkNum,1);
                  else
                     map.put(chkNum, map.get(chkNum)+1);
              }

         }

         for (Object key : map.keySet()) 
             System.out.println(map.get(key) + " matches found "+key.toString());

Leave a Reply

Your email address will not be published. Required fields are marked *