Results 1 to 3 of 3
Thread: Pick a random value from array?
- 04-25-2011, 07:55 PM #1
Member
- Join Date
- Apr 2011
- Posts
- 7
- Rep Power
- 0
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:
In the communicate(); method, I want it to pick a random value from the array communicationMethods. How?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; } }
- 04-25-2011, 08:04 PM #2
This should give you some ideas: Random (Java Platform SE 6)
- 04-26-2011, 05:36 AM #3
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,
Hope that helps,Java Code:int arrayLength = communicationMethods.length; int random = (int) (Math.random() * arrayLength); System.out.println("Random Array Element : " + communicationMethods[random]);
GoldestJava Is A Funny Language... Really!.gif)
Click on * and add to member reputation, if you find their advices/solutions effective.
Similar Threads
-
Pick random array index and change the element value
By Space Ranger in forum New To JavaReplies: 8Last Post: 03-29-2011, 10:18 PM -
Array of random numbers ...
By shane1987 in forum New To JavaReplies: 31Last Post: 11-14-2010, 09:33 PM -
Help with random bits array
By AnimeKitty in forum New To JavaReplies: 11Last Post: 07-30-2010, 04:37 AM -
2D Array Random Shuffle
By Nuluvius in forum New To JavaReplies: 8Last Post: 11-23-2008, 06:15 PM -
How to get a random value in an array
By Franneldort in forum New To JavaReplies: 21Last Post: 11-01-2008, 02:42 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks