Results 1 to 4 of 4
  1. #1
    drhinri is offline Member
    Join Date
    Feb 2011
    Posts
    4
    Rep Power
    0

    Exclamation How can you use a variable in a method that is declared in main?

    I'm trying to write a program in which i have several methods. I inputted an array of strings in main and want to use this array in both main and the methods. How do I go about doing this? I need to declare the variable in the method, but I need the original array to be the value of this.
    Thanks

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    The OO approach would be to create a class and declare your data as one or more instance variables. That way all methods will have access to them.

    If this is beyond your scope then you will have to pass your data as parameters.

  3. #3
    drhinri is offline Member
    Join Date
    Feb 2011
    Posts
    4
    Rep Power
    0

    Default

    thank you so much.
    Last edited by drhinri; 02-11-2011 at 02:41 AM.

  4. #4
    kbro3 is offline Member
    Join Date
    Feb 2011
    Posts
    24
    Rep Power
    0

    Default

    He means that you pass in your data as parameters to the methods:

    public int addTwo(int a, int b)
    {
    return a + b;

    }

    So in this example, you are passing two integers into your method (these are parameters). You could just as easily pass an array into your method.

    Cheers,

    Kirill

Similar Threads

  1. Calling The main method from another method
    By SwissR in forum New To Java
    Replies: 3
    Last Post: 07-27-2010, 11:03 AM
  2. Replies: 2
    Last Post: 12-05-2009, 11:24 AM
  3. calling method from main method
    By bob_bee in forum New To Java
    Replies: 4
    Last Post: 10-02-2009, 05:30 PM
  4. Replies: 5
    Last Post: 10-06-2008, 12:11 AM
  5. Calling a variable from main to another class
    By itsme in forum New To Java
    Replies: 1
    Last Post: 12-18-2007, 03:35 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •