okay ive been trying to do this for some time i want my program to randomly select 3 strings from my text file and display them randomly so each time i press 9 on my menu it will display 3 different ones each time and i've already made the array i'm just trying to figure out this last part :)

//the array name words[3];
Random random = new Random();
int rgen = random.nextInt(10)+1;
System.out.println(words[rgen]);

Recommended Answers

All 4 Replies

Is your file already in memory or are you retrieving new strings from the file each time?

Please post some code, it s really hard to think without seeing the actual code

and remember that your requirement to show 3 DIFFERENT ones each time means you're not looking at something random. If it were random, there'd be a chance of the same showing up multiple times.

ok so your going to need a loop surrounding your statements so that 3 items can be selected

private String[] mainArray = new String[10];
private String[] threeStrings = new String[3];

public void getThreeRandomStrings()
{
    Random rand = new Random();

    for(int i = 0; i < 3; i++)
    {
        threeStrings[i] = mainArray[rand.nextInt(10)];
    }
}

This example does not take into consideration the fact that the Random object may produce the same integer twice which would lead to a String in mainArray being selected twice in a single allocation. This wouldn't cause an error, however it may mess with any further operations you wish to execute.

Hope this was helpful

If not you can DM me for further assistance or reply to this thread.

Good Luck

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.