Hi. Can somebody help me? I am trying to create a program that reads random line from a file and displays them.
My problem is, it keeps repeating the same line after a few tries. i have 8 total lines from my file...

this is my code so far...

public static String getWord()
{
	int randNum;
	String quests = " ";
	try
	{
		Scanner inFile = new Scanner(new FileReader("game.txt"));
		randNum = (int) (Math.random() * 8);
		for(int i = 0; i<=randNum-1; i++)
		quests = inFile.nextLine();
		return quests;	
	} 
	catch(Exception e)
	{
		System.exit(-1);
	}	
	return quests;
}

thanks in advance! :)

Recommended Answers

All 8 Replies

well you have only 8 possible numbers to generate so the probability of repetition is high; use the java.util.Random#nextInt(8) its no different from math.random() but it saves you the extra multiplication

If you don't want repeats, then you will need to keep track of what has been read so far, and skip reading that one again.
If the number of records are known, you could use a boolean array to keep track of what has been read.

@ejosiah do you mean like this?

Random randomGenerator = new Random();
randNum = randomGenerator.nextInt(8);

..it doesn't work for me.. it keeps on repeating the same line after few tries.. :(

@NormR1 can you give me an example using boolean array?

im new to java.. so i really dont know how to use those methods..

There is no guarantee that the numbers returned in a short sequence will not repeat.
You will need to detect and reject duplicates.

Another way is create a list of the numbers to use, shuffle the list and then remove the numbers one at a time. Guaranteed to have no duplicates.

Use the record number as an index into the array. Test if the array's element is set, if it is, skip the number. If not set, set it and use the number.

Look at this example and then u should be able to solve your problem

List<Integer> list = new ArrayList<Integer>();
		
		// add the numbers 1 to 8 to your list
		for(int i = 1; i <= 8; i++){
			list.add(i);
		}
		
		// shuffle the list and remove the first item
		// to guarantee no repeats
		while(!list.isEmpty()){
			Collections.shuffle(list);
			Integer number = list.remove(0); // remove the first element
			System.out.println(number);
		}

thanks guys! instead of an array list of integer.. i used strings.. and it worked! thanks again!! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.