Results 1 to 3 of 3
  1. #1
    RattleSnake is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default Pick a random value from array?

    Hey guys,

    I'm very new to Java and I wanted to know how to pick a random value from an array?

    Here's my sourcecode:

    Java Code:
    public class Fad {
    
    	public static String[] communicationMethods = { "Facebook", "Phone", "SMS", "MSN" };
    	public static String name = ("Fad");
    	public static String mood;
    	public static int lastSpoken; // last spoken in days
    	public static boolean spokenRecently;
    	public static boolean bored;
    	public static boolean shouldSendMessage;
    	
    	public static void main(String[] args) {
    		checkLastChat();
    		communicate();
    
    	}
    	public static void checkLastChat() {
    		if ((lastSpoken < 3) && (name.equals("Fad"))) {
    			mood = ("sad");
    			bored = true;
    		}
    
    	}
    	public static void communicate() {
    		if (lastSpoken < 3);
    		shouldSendMessage = true;
    		}
    }
    In the communicate(); method, I want it to pick a random value from the array communicationMethods. How?

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default

    This should give you some ideas: Random (Java Platform SE 6)

  3. #3
    goldest's Avatar
    goldest is offline Senior Member
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    469
    Rep Power
    5

    Wink

    You can directly use the Math.random() method to generate a random number in a specific range. By using that number, you can access the array elements later on.

    Something like,

    Java Code:
    int arrayLength = communicationMethods.length;
    int random = (int) (Math.random() * arrayLength);
    System.out.println("Random Array Element : " + communicationMethods[random]);
    Hope that helps,

    Goldest
    Java Is A Funny Language... Really!
    Click on * and add to member reputation, if you find their advices/solutions effective.

Similar Threads

  1. Pick random array index and change the element value
    By Space Ranger in forum New To Java
    Replies: 8
    Last Post: 03-29-2011, 10:18 PM
  2. Array of random numbers ...
    By shane1987 in forum New To Java
    Replies: 31
    Last Post: 11-14-2010, 09:33 PM
  3. Help with random bits array
    By AnimeKitty in forum New To Java
    Replies: 11
    Last Post: 07-30-2010, 04:37 AM
  4. 2D Array Random Shuffle
    By Nuluvius in forum New To Java
    Replies: 8
    Last Post: 11-23-2008, 06:15 PM
  5. How to get a random value in an array
    By Franneldort in forum New To Java
    Replies: 21
    Last Post: 11-01-2008, 02:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •