How to search for a number in two-dimensional array of integers in Java

2 Answers

0 votes
package javaapplication1;

public class Example {
    public static void main(String[] args) {
             
         int[][] array2D = { 
            { 19, 23, 10, 78 },
            { 98, 80, 22, 44 },
            { 31, 32, 21, 99 }               
        };
        int searchNumber  = 80;
        int i;
        int j = 0;
        boolean found = false;
 
        search_loop_label:
        for (i = 0; i < array2D.length; i++) {
            for (j = 0; j < array2D[i].length; j++) {
                if (array2D[i][j] == searchNumber) {
                    found = true;
                    break search_loop_label;
                }
            }
        }
 
        if (found) 
            System.out.println("Found in " + "array2D[" + i + "][" + j + "]");
        else 
            System.out.println("Not Found");
    }
}


/*
run:
 
Found in array2D[1][1]
 
*/

 



answered Jan 14, 2016 by avibootz
edited Jan 14, 2016 by avibootz
0 votes
package javaapplication1;

public class Example {
    public static void main(String[] args) {
             
         int[][] array2D = { 
            { 19, 23, 10, 78 },
            { 98, 80, 22, 44 },
            { 31, 32, 21, 99 }               
        };
        int searchNumber  = 80;
 
        if (arraySearch(array2D, searchNumber) == true) 
            System.out.println("Found");
        else
            System.out.println("Not Found");
    }
    public static boolean arraySearch(int[][] array2D, int val) {
        for (int[] array1D : array2D) {
            for (int item : array1D) {
                if (item == val)
                    return true;
            }
        }
        return false;
    }
}


/*
run:
 
Found
 
*/

 



answered Jan 14, 2016 by avibootz
edited Jan 14, 2016 by avibootz
...