Hi, i'm having a bit of trouble understanding how you use variables in different methods. For example im getting some information from the user in 1 method and storing it in an arraylist. In another method i want to display the information from the arraylist, but it says that it can't find the variable or arraylist. How do i use the same information and variables in different methods? Can someone include example code to explain please?
Using variables in different methods?
Page 1 of 13 Replies - 1199 Views - Last Post: 22 November 2009 - 09:06 PM
Replies To: Using variables in different methods?
#2
Re: Using variables in different methods?
Posted 22 November 2009 - 12:19 PM
Variables created inside methods ("local variables") are not accessible outside of the method. The fix for this is to use a class variable that both methods can then access. The pseudo code might look something like this:
public class Example{
private ArrayList input;
public void setInput(){
//take your user input and store it in the variable input
}
public void doSomething(){
//do something with input
}
}
#3
Re: Using variables in different methods?
Posted 22 November 2009 - 02:35 PM
So whats the command or how do you access the class variables from the methods?
#4
Re: Using variables in different methods?
Posted 22 November 2009 - 09:06 PM
assigning values etc is exactly the same as it would be any other time, just make sure that the variable is initialized
private ArrayList input;
public void setInput(){
input=new ArrayList();
//add stuff to input like input.add(index, object);
}
public void doSomething(){
//do something with input like input.get(index);
}
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote




|