• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling an array to Main  RSS feed

 
Taylor Hall
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
So i have two classes, Main & ListOfAges. I am able to put the information from an .dat file and place it into an array, but I am struggling to figure out how to access that array in Main. Below is my ListOfAges class. Somebody, anybody, please help!

PREFACE { I simply want to display a list of 200 numbers in Main by calling or accessing the array below:}
========================================================================

 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Why do you want to access that array in the main method at all? The idea behind a main method is to start your application off. Once that is done, pass control to other objects.
Why do you want access to that array anywhere else? If you need things like totals, averages, counts, let the class with the array do all that.

By the way, get rid of that empty constructor. Well, I think you should. That is (probably) where you should be initialising your array and ageCount (even if you are initialising it to the same as its default value of 0). And don't re‑declare a shadowing variable as you have in line 11.
 
Taylor Hall
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for your response.
It makes since not to call it from main. I just want to display the numbers in a separate method. I know i could easily output each age as the loop passes, but what i want to do is gather all of the ages i loaded, then display them in a method like 'displayAges()'
any thoughts?
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create a loop to display all the ages. You can copy the array to a smaller array and iterate that. You can use methods of the Arrays class to do the copying. Or to create a String to display. Or both.
There are doubtless many other possibilities.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't like the idea of an array too large to hold all the numbers. A List<Integer> would be better, but you may not know about Lists yet. Unfortunately I don't think there is a straightforward way to predict the size of the buffer in advance. The nearest is you can read every int in the file and do nothing with it, but count how many there are. Then you would have to read the entire file again once you know how many items it contains. So I don't think there is a really good solution to that problem.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!