Welcome to Dream.In.Code
Become a Java Expert!

Join 150,375 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,611 people online right now. Registration is fast and FREE... Join Now!




Random String array generation

 
Reply to this topicStart new topic

Random String array generation

Nyarlathotep333
8 Feb, 2008 - 03:34 PM
Post #1

New D.I.C Head
*

Joined: 7 Feb, 2008
Posts: 2

OK, so I'm fairly new to Java programming and I'm experiencing a problem with randomly generating a result from a String array.

I've got an applet I'm working on which will have a JButton and a JTextArea. The JButton will generate a few things in the JTextArea each time it is pressed and one of the things I'd like it to generate is a random text from my String array. It works just fine the first time the button is pressed...in that it generates a random result from the array, but when the button is pressed another time it will display the first random result again instead of a new random result.

I've got a similar method of generating random numbers that works just fine, it's just for some reason when I use the String array it does this. Am I just missing something?

Here is the code for the random String array generation:

CODE
import java.util.Random;

public class stringList {
    
    String[] sList = { "item 1", "item 2", "item 3", "item 4"};
    
    Random s = new Random();
    int Select = 0;
    
    String list = sList[produceNumber()];
        
    public int produceNumber()
    {
    
        Select = (s.nextInt(sList.length));
        
        return Select;
    }
}

User is offlineProfile CardPM
+Quote Post

capty99
RE: Random String Array Generation
8 Feb, 2008 - 03:58 PM
Post #2

the real kya
Group Icon

Joined: 26 Apr, 2001
Posts: 9,259



Thanked: 16 times
Dream Kudos: 550
My Contributions
i'm sorry to not be of more help, its been too long since i've used java effectively,
CODE

but a workaround that DOES work is to throw in a new method
    public String pickItem()
    {
       return sList[s.nextInt(sList.length)];
    }

and just call that.

throw this in your main method :
CODE

stringList lister = new stringList();
System.out.println(lister.pickItem());

and run it a couple times and it works.

This post has been edited by capty99: 8 Feb, 2008 - 03:59 PM
User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 03:05PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month