• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting objects in an array to count to 10  RSS feed

 
davey smithy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to get student objects in an array to count to 10, I have created a getCounter() method which counts from 0 - 9, but I want each of the student objects to count from 1 - 10. So for example the outcome that I am expecting is:
MathStudent[1] - John: Count:1
MathStudent[2] - Marcus: Count: 1
...
ComputerStudent[3] - Alberto: Count: 1
...
Upto the point that all reach Count: 10


Also I have created the array in a thread class so it should sleep for 1 second in between the counts.

Below is the code I have in thread class:
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean you want a count of Student instances as they are created? Why does it have to be in the Student class? Can you do that elsewhere?

One way to do it in the Student class is to have a private static count field and increment it in the constructor. That counts how any objects have been created, but there is no straightforward way to count objects going out of scope or becoming unreachable.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest a different way to create that array: an array initialiser. That ensures your array is always the right size with no risk of overflowing its bounds nor of having a null in it anywhere. I would also suggest you don't write 10 anywhere in your loops. Write myArray.length instead. Or even better use a for‑each loop (=enhanced for loop).
Is there a particular reason for wanting to extend Thre‍ad? You can simply write Thread.sleep(...) but beware: that method declares a checked Exception.
Whenever you declare an array put the [] before the array's name. It is part of the type, so it shou‍ld read Student[].
But s is a bad name for a variable, because it is not obvious what it means.
What are you doing with the counter in line 23? You appear to have a counter but you aren't doing anything with it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!