/* * One dimensional array. Passing arrays as parameters * Two class - OOP. * Searches the whole array for every occurance of a specific value * NOTE: The search value apprears in more than one place in the array * The foundArr will hold the position indexes of where the value has been * found. Position indexes are from zero to end. * The value -1 indicates "not found" */ package book2ConstructsE; public class ArrayAndSearchUI { public static void main(String[] args) { // One dimensional array int[] theArray = {1, 13, 5, 1, 2, 5, 1, 2, 5, 2, 7, 2}; int searchValue = 2; String foundStr = "The Value " + searchValue + " was found in position: "; // A one dimensional array big enough to contain all the values // of the original. This array will hold the indexes of where the // value has been found in the array - -1 if not found int indexNumber = theArray.length; int[] foundArr = new int[indexNumber]; ArrayAndSearchManager lm = new ArrayAndSearchManager(); foundArr = lm.find(searchValue, theArray); // "Not found" in indexed position is indicated by -1 for (int i = 0; i < foundArr.length; i++) { if (foundArr[i] != -1) foundStr = foundStr + foundArr[i] + ", "; } System.out.println(foundStr); } // end main } // end class =============================================================================== package book2ConstructsE; public class ArrayAndSearchManager { // Accepts the search value and the array to be searched // If found - returns an array with the found position. public int[] find(int searchValue, int[] theArray) { // A one dimensional array big enough to contain all the values // of the original. This array will hold the indexes of where the // value has been found in the array - -1 if not found int indexNumber = theArray.length; int[] foundArr = new int[indexNumber]; // Using negative one as a not found value for (int i = 0; i < indexNumber; i++) foundArr[i] = -1; for (int i = 0; i < theArray.length; i++) { if (theArray[i] == searchValue) foundArr[i] = i; } // end for return foundArr; } } ================================================================================== OUTPUT run: The Value 2 was found in position: 4, 7, 9, 11, BUILD SUCCESSFUL (total time: 0 seconds)