wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Using the Random Method: How to use random numbers to represent other values? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using the Random Method: How to use random numbers to represent other values?" Watch "Using the Random Method: How to use random numbers to represent other values?" New topic
Author

Using the Random Method: How to use random numbers to represent other values?

Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Hi, I'm writing a program that generates a random place. The random places are listed in three different text files. My program asks the user to enter a text file, and then asks for a random seed, and then it will generate a random place from the file they chose.

I'm unsure how to use the file they chose and how to obtain a random place from it, using the number they chose

Please help!
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
My code so far:

Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

You only need to call nextInt() once, not in a loop.

If you want to provide an explicit seed (not generally necessary), then you would pass it to then Random constructor.

I also don't know what you mean by a random "place" in the file. Do you mean a random line? If so, you need to read the file into memory first (assuming it's small enough to do so) so that you can find out how many lines it has, and then use that number to pass to Random.nextInt() to set the range of the random number to choose.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Oh excuse me, I did mean random line.

I'm not sure if I completely understood what you said, but I tried to follow. I think I managed to read the files into memory. I was wondering how I could now generate a random line in the file from their seed.

Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Is a for loop necessary to do this?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

1. Read in the entire file, a line at a time. Put the lines into an array or ArrayList (preferably ArrayList). A loop is needed for this.

2. Generate a single random number, using Random.nextInt(int). Read the docs for that method to see what that int means, and how it relates to what you're doing. No loop here.

3. Use the number from step 2 as an index into the list or array, to select the line. No loop here.

Note that you can and should write, debug, and test each of the above completely independently from the others. Each step can be written and tested as if the others didn't even exist, harcoding stuff where necessary as placeholders for what would come from the other pieces. One way to do that is to write 3 separate programs. Once all the pieces work separately, you can combine them.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
I've got the number down but I don't know how to start step 3. How do I select and print the line?
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Would I do the charAt the index?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:Would I do the charAt the index?

If you followed Jeffs suggestion, your ArrayList has lines not char. If I understand you correctly, one line represents one place. Check out the API docs for ArrayList to see if it has a method which will give you the data, if you provide it with an index (hint)


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)

Would I use this one?

I'm sorry for asking so many questions; I am just so frustrated
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:
I'm sorry for asking so many questions; I am just so frustrated

Don't let it bother you. Everyone was a beginner sometime. Going by your other questions, you are doing good.

Consider a traffic jam, starting off with an Audi, followed by Jaguar, BMW, Volvo, Mercedes....
You are the traffic cop. Your job is to let go one car at one time. From your perspective, the Audi is 1st, Jaguar 2nd and so on. 1st, 2nd etc are the indices.
Now think of your ArrayList as your road with the traffic jam and think of the places you read from the file instead of those cars. Now using the method you found, can you get the places, based on the index*?

*Indices in Java start with 0 and not 1
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
I see....I haven't got Arrays down because I have not learned them yet, so I was wondering how to read in multiple lines into an ArrayList
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28


I'm pretty sure I'm doing this very wrong haha
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:I see....I haven't got Arrays down because I have not learned them yet, so I was wondering how to read in multiple lines into an ArrayList


Assumption: Each line in the places file is a place

Pseudo code
1) Ask user for file
2) Check if file exists
3) If not, inform user and ask for another one
4) If exists, create a new ArrayList
5) Start reading the file one line at a time (which is presumed to be one place)
6) After reading each place, add it to the ArrayList
7) Continue till end of file. Now the ArrayList should be full of places you read from the file
8) Check the ArrayList size
9) Generate a Random number (check the API which will limit the random number to be equal/less than the available places)
10) Retrieve place matching the number from the ArrayList
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Ahhh excuse me, I meant multiple files into an ArrayList
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:Ahhh excuse me, I meant multiple files into an ArrayList

You don't really need to do that do you? Your requirement is to randomize a place from one file.
....and then it will generate a random place from the file they chose.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
I apologize if I'm poor at explaining this.

My program is supposed to generate a random city. I have three files, and each file contains a different list of cities.

It prompts the user for one of the three files. When they type in a file that exists, my program is supposed to then ask for a seed, and then it will use that seed to randomly select an index within the file that they chose, and the program will then print out a random city from the file.

I am stuck at how to generate the random city from the seed provided by the user. I am very confused because the files that do exist only have a few lines. But my program is supposed to be able to print out a random city, even if the seed is larger than the number of lines in the file
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:
I am stuck at how to generate the random city from the seed provided by the user. I am very confused because the files that do exist only have a few lines. But my program is supposed to be able to print out a random city, even if the seed is larger than the number of lines in the file

Jeff already told you above, how to use the seed.
The seed is NOT the random number, but it is used to generate the random number.

There can be several ways how to chose the city if the random number generated is bigger than the number of cities.
Think of the cities as circular. i.e. Last city is followed by the first, first by second etc. Keep on counting till you reach the random number.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
When you say circular, it makes me think I have to use a loop. Is ArrayList still necessary for this? In my head is to use a for loop and I am trying to go about this with it. I have my random number generated from the seed and want to use it in the for loop.


Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:When you say circular, it makes me think I have to use a loop. Is ArrayList still necessary for this? In my head is to use a for loop and I am trying to go about this with it

You will need some kind of data structure to hold the read lines. You dont want to keep reading them every time from the while. Read, put them in some data structure and process the structure.
Problem with arrays is that you need to define their size when you create them. ArrayList is more dynamic.

You can either run the loop or do some math to identify the city. At this stage, I would recommend the loop.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Would I need to nest loops because of my multiple files?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Tracy Villa wrote:Would I need to nest loops because of my multiple files?

Huh? Why multiple files?

Tracy Villa wrote:
t prompts the user for one of the three files. When they type in a file that exists, my program is supposed to then ask for a seed, and then it will use that seed to randomly select an index within the file that they chose, and the program will then print out a random city from the file.

You need to process only the user specified file.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Tracy Villa wrote:Would I need to nest loops because of my multiple files?


No. You already said the user picks a file. If you have files W, X, Y, and Z, and the user picks Y, you don't need to loop to get to file Y. A loop is for doing something multiple times, such as when you put "read one line from a file" into a loop, it reads multiple lines from the file.

You say you don't want to use arrays or Lists because you haven't learned them yet. Are you not allowed to use them, or do you just not want to? Using one will make it easier, but it can be done without it.

With a List:
=======
1. Loop over the file, a line at a time, adding each line to the list as we go.
2. Check the list's size to see how many lines we have.
3. Use the number of lines in our call to Random.nextInt(int n) to get a random number corresponding to the line number that we will randomly choose. (IMPORTANT: Do you understand what I mean here?)
4. User the random number generated in #3 as the index of the line to select from the list.


Without a List, approach 1:
================
We don't know how many lines the file has, so we can't use that for Random.nextInt(int n), at least not as easily.
1. Loop over the file, a line at a time, but don't store the lines, just ignore the content and increment a counter for each line.
2. When we've read the whole file, our counter will tell us the number of lines in the file.
3. Use the value of the counter with Random.nextInt(int n) to get a random number corresponding to the line number that we will randomly choose.
4. Start reading the file again, a line at a time, ignoring the lines and incrementing a counter, until the counter reaches the random number from #3. We now have the randomly chosen Nth line in the file.


Without a List, approach 2:
=================
Similar to the above approach. It's the already suggested approach of continuing to read the file from the beginning until we reach the randomly chosen number. If the file is 100 lines long, and the randomly chosen number is 123,456,789, we'll be reading the file 1,234,568 times, and on the last time, we'll stop at line 89. This requires a nested loop. The inner loop keeps going as long as there are more lines in the file, and the outer loop calls the inner loop to start over from the beginning of the file as long as our total number of lines read is less than the random number chosen.

Note that with this approach, since we have no idea how many lines are in the file, we have to use nextInt(), not nextInt(int n). (Do you understand why?) That means we could end up having to read the file millions of times just to get to the random number. If you know some upper bound on the number of lines--such as "There's no way any of the files will be more than 500 lines long", you could use that for nextInt(int n), but that will make your results somewhat less random.


Finally, you've mentioned a seed a couple of times, but I think you're misunderstanding what that term means. A seed is the number given to the random number generator (the Random instance you're creating) to tell it where to start its sequence from. It's impossible to get truly random numbers purely with software. The Random class is a pseudo-random number generator. It will provide a decent enough distribution for many cases, but if we know its current value, we can predict its next one. The seed is not necessary. The only reason I know of to use it is if we want to reproduce the same sequence of numbers multiple times in a row, so as to exactly reproduce a test scenario so that we can eliminate one variable when observing how changes we make affect the behavior of our code.

Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Thank you very much for the explanation. Also thank you all for your patience!

I'm trying to avoid using arrays and Lists because I'm uncomfortable with them and am more familiar with loops.

Your approach 2 is the one I'm trying to achieve. I think I grasp the gist of what you are saying, but am still trying to completely comprehend it. Am I approaching this correctly?



Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Tracy Villa wrote:
I'm trying to avoid using arrays and Lists because I'm uncomfortable with them


This would be a great opportunity to start getting familiar with them then.

Your approach 2 is the one I'm trying to achieve.


Er, which one?

A) The second one listed, labeled "Without list approach 1" (which is what your code below looks like)?
B) The third one listed, labeled "Without list approach 2"?

I think I grasp the gist of what you are saying, but am still trying to completely comprehend it. Am I approaching this correctly?




For #A (w/o list approach 1), you're close. That "if" is totally unnecessary, and I don't know what you're trying to accomplish with it. Your "i" variable is your counter, and you just keep looping until it reaches the random number. Get rid of the "if" and the "counter" variable.

If you're talking about #B (w/o list approach 2), then, sorry to say, you're way off.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
Oops x_x I was trying to do #B without list approach 2

Could I get a hint how to start B? If I understand correctly, I would start it similar to #A, and would be using


Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Tracy Villa wrote:Oops x_x I was trying to do #B without list approach 2

Could I get a hint how to start B? If I understand correctly, I would start it similar to #A, and would be using




Go back and read what I said closely. You need nested loops. If your random number is a million and you have a 100-line file, that loop you have will be calling nextLine() 999,900 times when there are no more lines. (Although I think Scanner.nextLine() actually throws an exception in that case, so you'd call it once to many times, get the exception and your program would die.)

Your outer loop condition needs to say, "keep going as long as we haven't reached the random number". The inner loop condition needs to be "keep going as long as there are more lines in the file and we haven't yet reached the random number."

Honestly, I think you've picked the ugliest and most difficult of the 3 approaches, and I'm reluctant to provide any more help with what I consider to be a bad design.
Tracy Villa
Greenhorn

Joined: Nov 03, 2012
Posts: 28
I apologize; I would take the time to learn arrays right now but I'm a slow learner, and this project is overdue and so I am just using the most familiar method to me so I can get it over with as soon as possible >_<

I tried this


But it always has the same output, no matter what random number I put in. Did I do something wrong with my while loop?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Tracy Villa wrote:I apologize; I would take the time to learn arrays right now but I'm a slow learner, and this project is overdue and so I am just using the most familiar method to me so I can get it over with as soon as possible >_<


You're probably not really saving any time. Look how long it's taking to do it this way.


I tried this


But it always has the same output, no matter what random number I put in. Did I do something wrong with my while loop?


Look closely at your inner loop. Tell me in English exactly what you think it does.

(You're taking the approach that's the most difficult to understand (without regard to Java) just to avoid learning a Java concept that you're going to have to learn anyway. Understanding and describing the approach precisely, without regard to any programming language, is usually harder than actually writing the code. I don't think you fully understand this approach in the abstract, and it's showing up in your code.)

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using the Random Method: How to use random numbers to represent other values?
 
Similar Threads
PLEASE HELP
Help! How to design this mutithreading application??
StreamTokenizer
problem with random access file
Save variables from a Randomly choosen line in a input file?