Passing Variables from a class to another class

Hi,

What I need is to pass variables defined in "Class1" to "Class2" so that they can be used by "Class2", such as an array of items.

A sample code of what I need would be :

import java.io.*;

import java.util.*;

public class Test extends java.applet.Applet{

//-The list of items is put in an Array--//

public class List {

int nbItems = 0;

//Variables I need to reuse//

String[] itemname = new String[50];

void Acquire(){

try{

FileReader source = new FileReader("sourcetext.txt");

BufferedReader buff = new BufferedReader(source);

boolean eof = false;

while(!eof){

String line=buff.readLine();

if(line == null)

eof = true;

else{

StringTokenizer st = new StringTokenizer(line,";");

itemname[nbItems] = st.nextToken();

}

nbItems++;

}

buff.close();

}catch(IOException e){

System.out.println("File Error");

}catch(SecurityException s){

System.out.println("Unauthorized Access");

}

}

}

// I need to reuse variables below (at least) //

public void init(){

List newlist = new List();

newlist.Acquire();

// From now, how can I reuse itemname[] which I defined in the Acquire method so that I can use it in a spreadsheet, or in a Choice or in whatever I need to use it ? //

// I think I would use something like: for(i=0;i<=itemname.length;i++){...} //

}

}

I hope I was clear enough for you to understand my needs, and that you will be able to give me helpful hints or codes.

Thanx in advance !

stephmor

[1699 byte] By [stephmor] at [2007-9-26 1:21:15]
# 1

Not totally sure I understand your question ... but typically, you would do something like this:

public class List {

private String[] itemname = new String[50];

// Public Accessors

public String getItemName() {

return itemname;

}

public void setItemName(String[] itemname) {

this.itemname = itemname;

}

... rest of your code for that class

}

Then in your init method:

List newlist = new List();

newlist.Acquire();

String[] items = newlist.getItemName(); // Get the items

for (int j = 0; j < items.length; j++) {

// Do something with the item

System.out.println("Item" + i + ": " + items[j]);

}

Hope that helps.

mazy_dar at 2007-6-29 0:56:42 > top of Java-index,Archived Forums,Java Programming...
# 2
Thanks a lot !This was very helpful to me .I hope I can help you back another time .stephmorNB: you got the cyber-dollars !
stephmor at 2007-6-29 0:56:42 > top of Java-index,Archived Forums,Java Programming...