Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Saving variable values in classes

Status
Not open for further replies.

MaxGeek

Technical User
Jan 8, 2004
52
US
I'm trying to create a class that returns a random number. However I want it to continue to return that same random number 4 times before finding a new random number and returning that 4 times and etc.

My problem is that I'm having trouble saving that random number in the class. Right now I'm trying to use an ArrayList to save that random number so I can return it four times, but I was wonder if anyone knew a better way I could do this.
 
Something like this?
Code:
public class RandomValue
{
  java.util.Random r;
  int num, current, max;
  public RandomValue(int m)
  {
    r = new java.util.Random();
    num = 0;
    current = -1;
    max = m;
  }
  public int getRandom()
  {
    num++;
    if (num == 4)
    {
      current = r.nextInt(max);
      num = 0;
    }
    return current;
  }
}
This keeps track of a current value and a number of times it has been called. If it has been called four times, the number and counter are reset. Is this what you meant at all?

--Chessbot

There is a level of Hell reserved for probability theorists in which every monkey that types on a typewriter produces a Shakespearean sonnet.
 
Thanks thats pretty much what I was looking for. I did something like that at first but for some reason I didn't think it was keeping the values of the new variables.
 
Unless you are redeclaring it each time, it should retain the values...

--Chessbot

There is a level of Hell reserved for probability theorists in which every monkey that types on a typewriter produces a Shakespearean sonnet.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top