/* * Two dimensional array * Two class - OOP * Search algorithm without labels and break * Passing arrays as parameters * NOTE: The search value is to be found in more than one place in the * two diminsional array. * Without break and a label the search will always output the last occurance */ package book2constructsC; public class LabelsAndLoopsCUI { public static void main(String[] args) { // Two dimensional array - first index, second index int [][] list = {{1,13,5}, {1,2,5}, {1,2,5}, {2,7,2}}; // Minus one - searchValue not found int [] coOrds = {-1,-1}; int searchValue = 19; LablesAndLoopsCManager lm = new LablesAndLoopsCManager(); coOrds = lm.find(searchValue, list); // Easier to report "not found" first if(coOrds[0] == -1 || coOrds[1] == -1) System.out.println("Value " + searchValue + " not found."); else System.out.println("Value " + searchValue + " found at " + "(" + coOrds[0] + "," + coOrds[1] + ")"); } // end main } // end class ================================================================================= package book2constructsC; public class LablesAndLoopsCManager { // Accepts the search value and the array to be searched // If found - returns an array with the found co-ords. public int[]find(int searchValue, int[][] theArray) { // Minus one - searchValue not found int [] coOrds = {-1,-1}; // Two dimensional array - list [first index, second index] // Outer loop goes for the duration of the whole array - both indexes // Inner loop goes for the duration of the first index only for (int i = 0; i < theArray.length;i++) { for (int j = 0; j < theArray[i].length; j++) { if (theArray[i][j] == searchValue){ coOrds[0] = i; coOrds[1] = j; } // end if } // inner loop } // outer loop return coOrds; } // end find } // end class =============================================================================== OUTPUT - search for 19 run: Value 19 not found. BUILD SUCCESSFUL (total time: 1 second) OUTPUT - search for 2 (to be found in more than one place) Without labels and break will always report the last occurance. run: Value 2 found at (3,2) BUILD SUCCESSFUL (total time: 1 second)