Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Calling Element of Array from Different Class

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Calling Element of Array from Different Class

    Hey there,
    So I just finished up my term project and have everything working but I wanted to make one slight adjustment to the code and Im not exactly sure what I'm doing wrong - it involves retrieving a set element from an array from a different class so to some what show what I have going on:

    public class example1
    {
    private example2 Examp;
     
    public example1()
    {
    Examp = new example2();
    }
     
    public void getArray()
    {
    if(Var >= 10 && Var <= 20) {
    System.out.println(?) }
    }
     
    }

    2nd Class the array is in

    public class example2
    {
    private String array[];
     
    public example2()
    {
    Array = new String[10]
    genArray()
    }
     
    public void genArray()
    {
    Array[0]="Some Text here"
    Array[1]="Some Text here"
    Array[2]="Some Text here"
    }
     
    /**
    *I was thinking something like this but I would rather just input the index # is all to retrive
    *the corresponding code in the array
    */
    public String get(String[] Array, int index)
    {
    return Array[index];
    }
     
    }

    I have an if statement that looks at a sum of numbers, and predetermined upon the set of numbers I want it to output a message by calling the index number in the array and returning the string. I currently just have the message in the if statements but would be nicer to just pull them from a different class to keep it consolidated

    Thanks for the help


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Calling Element of Array from Different Class

    The code you posted lost its formatting. Perhaps you added the code tags after posting unformatted code. Next time, copy the formatted code directly from your editor and post between code tags OR post the code and then add the code tags at both ends.

    I notice you have a getArray() method with a return type of 'void'. Methods that 'get' something would typically return something.

    Your last method (reformatted and posted here
    /**
     *I was thinking something like this but I would rather just input the index
     *# is all to retrive the corresponding code in the array
     */
    public String get(String[] Array, int index)
    {
        return Array[index];
    }
    should work fine, but I'd give it a better name, like getArrayElement(). Or, if you'd like the method to return an element from a specific array as you described in the comment, then call it getNameArrayElement() (or whatever that array is), and then simply pass the method an index number.

  3. #3
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calling Element of Array from Different Class

    Thanks for the Reply I guess I wasn't clear on my first post, Ill see If I can clear this up a bit more in the 1st class I have an if loop that takes 2 numbers add it them together to spit out a random fortune based on the number as of right now I have:

        public int getFortune()
        {
            int sum = month + day;
            if(sum < 0 || sum > 43){
                System.out.println("A thrilling time is in your immediate future.");

    Now the problem is the System.out.println("said text here") <--- I don't want that text there, I know it works and does as it needs but I want all the fortunes located in a different class in a predefined array and I would like to be able to call something like
    System.out.println(className.getArray(1));

    and return the string related to the index of the Array in which is asked for, I'm lost as to what needs to go into each of the classes to make this happen. The code from my first post shows what I have so far and I have no idea if Im attacking this correctly or not, I have the program working I just wanted to make this little tweak and got lost while trying to do it. If you can give me an example of code that has to be in each class to achieve this that would be great!

    Thanks Again

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Calling Element of Array from Different Class

    public String get(String[] Array, int index)
    {
      return Array[index];
    }
    That code does NOT use the contents of the array defined in the class. it uses the String[] Array arg that was passed to the method. If the String[] arg is removed, then the code would access the array defined in the class.
    The code should range check the index to keep from getting an Array Index Out Of Bounds exception.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Calling Element of Array from Different Class

    Thank you So Much! That was it! Its hard to believe that String[] arg had me held up for so long and all I needed was to remove it and everything works now.

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Calling Element of Array from Different Class

    Figuring out class-to-class communication is always a big hurdle, and it shouldn't be. You've certainly already been doing it without realizing it. You'll laugh at yourself later, after you've figured out how simple it is, just as you'd chuckle at watching yourself learn to crawl, walk, etc.

    Based on your latest description, I imagine you'd like a class called Fortune that simply contains a collection of all possible fortunes and the methods needed to add, remove, or randomly obtain fortunes from the collection. Then, from an instance of the class, fortunes would be obtained using the appropriate Fortune method. I've roughed out what the Fortune class might look like below.

    Your other class would then create an instance of Fortune, let's call it fortune, and then use that to obtain a fortune from the collection at the index that has been randomly generated:

    String randomFortune = fortune.getAFortuneAtIndex( randomIndex );

    Let us know if you still have questions.
    public class Fortune
    {
        // instance variables
        String[] fortunes;
     
        // or it could be an ArrayList:
        // List fortunes;
     
        // default constructor
        public Fortunes( int numberOfFortunes )
        {
            // initialize instance variables
            fortunes = new String[numberOfFortunes];
     
            // or using the ArrayList
            // fortunes = new ArrayList<String>();
     
        } // end default constructor
     
        // and then the necessary methods to maintain the list
     
        // gets a fortune from the collection of fortunes
        public String getAFortuneAtIndex( int index )
        {
            return fortunes[index];
     
            // or using the ArrayList
            // return fortunes.get( index );
     
        } // end method getAFortuneAtIndex()
     
        // etc. . . . .
     
    } // end class Fortune

Similar Threads

  1. Java, calling another public class from within the main class giving problems.
    By RandomGaisha in forum What's Wrong With My Code?
    Replies: 9
    Last Post: November 26th, 2012, 02:30 PM
  2. eliminating an element in array
    By hanazz69 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 15th, 2012, 05:33 AM
  3. add new element in array
    By allen_k in forum Collections and Generics
    Replies: 3
    Last Post: December 11th, 2011, 03:13 PM
  4. Calling a print method from another class (printing array)
    By Kaldanis in forum Object Oriented Programming
    Replies: 7
    Last Post: November 25th, 2011, 01:32 PM
  5. how to find an element in an array
    By humdinger in forum Collections and Generics
    Replies: 8
    Last Post: April 9th, 2010, 05:22 PM