Tuesday, July 14, 2009

Sharing an array between classes?

I have created a database class which creates a database object array with three objects in each index.





CODE


class Database


{





int answer = JOptionPane.YES_OPTION;


int count = 0;


final int ARRAY_SIZE = 12;





public Database(){








CD[] data = new CD[ARRAY_SIZE];


String[] search = new String[ARRAY_SIZE];





while (answer == JOptionPane.YES_OPTION)


{





String a;


String c;


int n;





a = JOptionPane.showInputDialog("Please, enter artist name");


c = JOptionPane.showInputDialog("Please, enter CD name");


n = Integer.parseInt(JOptionPane.showInputDi... enter total number of tracks"));





data[count] = new CD(a, c, n);


search[count]= new String(c);





answer = JOptionPane.showConfirmDialog(null, "Enter another record?",


"???", JOptionPane.YES_NO_OPTION);


count++;


}


}


}


I then created a new class called search that is supposed to search the array in my database class for whatever the user types in, which in this case is a cd name.





CODE


class Search


{


int result;


int ARRAY_SIZE=12;


String searchKey = JOptionPane.showInputDialog("Give me the name of a CD");





result = linearSearch(search, searchKey, ARRAY_SIZE);





if(result== -1)


{


JOptionPane.showMessageDialog(null,"KEY " + searchKey + " NOT FOUND");


}


else


{


JOptionPane.showMessageDialog(null,"KEY " + searchKey + " FOUND in position " + result);


}











public static int linearSearch(String[] search, String key, int sizeOfArray)


{


for (int counter = 0; counter %26lt; sizeOfArray; counter++)


{


if (search[counter].equalsIgnoreCase (key))


return counter;


}


return -1;


}


}


How do i get the array from the database class to the search class.





cheers

Sharing an array between classes?
1. create a main class. The main class creates a database object and a search object, and passes the database data structure to the search object.





2. move the search class inside the database class. The database datastructure could then be global to both classes.





3. use inheritance. keep the two classes seperate and have the search class extend the database class. You end up having two possible classes that can be declared: a base database, and a searchable database. In your search class you can access the database's data structure using super.search[]


No comments:

Post a Comment