3 Replies - 1426 Views - Last Post: 22 November 2009 - 09:06 PM Rate Topic: -----

#1 GiveMeYourBagel  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 24-September 09

Using variables in different methods?

Post icon  Posted 22 November 2009 - 11:38 AM

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?
Is This A Good Question/Topic? 0
  • +

Replies To: Using variables in different methods?

#2 RedPhoenix  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 10-November 09

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
	  }

}


Was This Post Helpful? 0
  • +
  • -

#3 GiveMeYourBagel  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 24-September 09

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?
Was This Post Helpful? 0
  • +
  • -

#4 RedPhoenix  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 10-November 09

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);
	  }




Was This Post Helpful? 0
  • +
  • -

Page 1 of 1