-6

This is how my text file looks

Cincinnati 
Oxford  
Chicago 
New York
Las Vegas 
Houston  
Detroit  
Miami  
Denver 
Boston

I want to populate an ArrayListCity randomly from the text file and then sort it with collections.sort. All of the cities from the text file should be in the array list, but in a different order each time the program is run.

BackSlash
  • 21,927
  • 22
  • 96
  • 136
CinCity
  • 149
  • 2
  • 10
  • 4
    homework should be attempted.... – Mitch Wheat Jun 18 '14 at 10:30
  • The homework only asks us to use collections.sort, I'm trying to take it a step in advance and learn something besides what they teach in class. So, thanks for the help. – CinCity Jun 18 '14 at 10:41
  • Don't try to read lines randomly from the file. Read lines from the file into an array, and _then_ randomly shuffle the lines. – Kenster Jun 18 '14 at 11:27

1 Answers1

1

Read the file sequentially - thats the easiest route.

Then randomly shuffle the collection.


Actually, another question. Could you use math.random() to look at the lines of the text file and if, lets say, the line 5 comes up then you remove it from the parameters you set for math.random()? It would pick from 0-9 and after the fifth line is used it would pick from 0-4,6-9

It is possible - but over complicates things. The best way to implement such a feature, is to have a 'pool' of numbers. (i.e. an arraylist of Integer objects), then you can use a Random number generator (between 0 and arrayList.size()) to get (and remove it from your arrayList too) one of these Integer objects. Then read that line. This approach needs several objects (Random, Arraylist, Integer, Reader).

At best, its overcomplicated for something so simple. Best thing to do, like I said, read each line and insert it into the arrayList. Then suffle.

Another take on this is, read each line, get the size of the arraylist and insert the new String, randomly within the arraylist. Heres some code:

arrayList.add(getRandomIndex(arrayList.size()),string);

public int getRandomIndex(int size){
    return ((int)Math.random()*size)
}
Community
  • 1
  • 1
Husman
  • 6,819
  • 9
  • 29
  • 47
  • I just needed a little direction. Thanks man! – CinCity Jun 18 '14 at 10:37
  • Actually, another question. Could you use math.random() to look at the lines of the text file and if, lets say, the line 5 comes up then you remove it from the parameters you set for math.random()? It would pick from 0-9 and after the fifth line is used it would pick from 0-4,6-9. – CinCity Jun 18 '14 at 10:43
  • I feel like adding the cities into the array list then shuffling defeats of the purpose of sorting them later. I think I'll have a go at the second example you gave me. Thanks for the advice man, I appreciate you taking time to throw ideas back and forth. – CinCity Jun 18 '14 at 11:15