Thursday, July 30, 2009

Java Programming - Help passing an array between methods?

I am trying to pass an array which has been declared in the main body to then be passed into a method, i seem to have this done the problem is using scanner to enter keyboard input and then return the array to the main body.


Any help will be greatly appreciated


thankyou

Java Programming - Help passing an array between methods?
Sounds like you've programmed a lot in C/C++. In java, think more in the line of objects that manipulate the environment and provide data, than moving chunks of data between processes like Fortran/ADA/C/C++/Assembly does.





Best bet would be to make a class or private subclass that handles the IO. Make the "array" some time of dynamic container like a vector, and make it a private member of the class.


Then the getDataFromScanner() method would just populate the member variable.





If you are multithreaded a little more work needs done, of course.














Here's how other objects would use a getter method to get the array.





//--- in the main body ---//





import java.util.Vector;


public class MainBody {





Vector %26lt;String%26gt; scannedData = new DataIO().getData("scanner");





}











//----------IO class--------------------


import java.util.Vector;;





public class DataIO {





private Vector %26lt;String%26gt; data;








public void getDataFromScanner(){


//do scanner stuff


//populate the data here


//data = results from scanner stuff


}








public synchronized Vector%26lt;String%26gt; getData(String type) {





if(type.equalsIgnoreCase("scanner")){


getDataFromScanner();


}


return data;


}








}


No comments:

Post a Comment