I am trying to make Java select 1 random string from a given list.
Example of the list of strings:
1153 3494 9509 2 0 0 0 0
1153 3487 9509 2 0 0 0 0
1153 3491 9525 2 0 0 0 0
1153 3464 9513 2 0 0 0 0
Each row is 1 string
The idea is that it selects one, waits a certain period (like 7200 seconds) and replaces the previous string with another random string from the list (could be the same). The loop is sort of infinite.
Does anyone knows how to do this?
Ps. I am pretty much noobie with java :S, so i am afraid just saying i should use an arraylist (for example) wont work :P
If you have a list/array of data and you want to select a random element from the list. The easiest would probably be to generate a random number with the Math.random (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html) function which is between 0 and the count of your list/array.
You can then create a Thread that runs forever and sleeps for 7200 seconds between executions that generates a new random number and replaces the old variable.
Just watch out for concurrency issues when using Multi-Threading, have a read at http://download.oracle.com/javase/tutorial/essential/concurrency/.
Update (Example):
Java has a list that can be used to add, and remove data as you want. Data can then by extracted by giving the list the index (number) where the data is located in the list.
So you would be creating a list, then generating a random number in the list's range (0 to the size of the list as the max). And then extracting the data from the list by giving the list your random index. A example would be:
Hope this makes a bit more sense, and on second thought the Random class in java.util . Would be easier to rap your head around.
Since you say you're new to Java, this is a complete sample class to select random elements from a string list:
Then, what do you want eventually to accomplish? With a similar code you could set a class variable, for example. Most probably you want to have a separate Thread that runs this code.