'Linear Search using modified 2D array

How do I fix the multiple prints of -1 in the last nested loop? I'm making a linear search for 2D array but when the number is found the -1 prints multiple times even tho my condition is -1 when the number isn't found.

import java.util.Scanner;

/**
 *
 * @author
 */
public class FindInGroup {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        StringBuilder output = new StringBuilder();

        System.out.print("Enter number of groups: ");
        int groups = scanner.nextInt(); //number of groups
        System.out.print("Enter number of elements to be search: ");
        int nSearch = scanner.nextInt();
        int[][] elements = new int[groups][];
        for (int i = 0; i < groups; i++) {
            System.out.printf("Enter number of elements for group %d: ", i + 1);
            elements[i] = new int[scanner.nextInt()];

            for (int j = 0; j < elements[i].length; j++) {
                System.out.print("Enter value: ");
                elements[i][j] = scanner.nextInt();
            }
        }
        //print the array System.out.println(Arrays.deepToString(elements));
        int[] search = new int[nSearch];
        for (int i = 0; i < nSearch; i++) {
            System.out.print("Enter number(s) to be search: ");
            search[i] = scanner.nextInt();
            for (int j = 0; j < groups; j++) {
                for (int k = 0; k < elements[j].length; k++) {
                    if (search[i] != elements[j][k]) {
                        System.out.println(-1);
                    }
                    else System.out.println("Found at group " + (j + 1));
                }
            }
        }
    }
}


Solution 1:[1]

Change this

if (search[i] != elements[j][k]) {
    System.out.println(-1);
  }
else 
   System.out.println("Found at group " + (j + 1));

To this

if (search[i] == elements[j][k]) 
{    
  System.out.println("Found at group " + (j + 1));
  return;
}

You should only care when you have found the element and break it there so it doesn't proceed after that point

Finally at the end of your main method

  System.out.println("Element not found");

Which will be called only if your for loop didn't return i.e element was not found

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1