Results 1 to 4 of 4
Thread: random string are duplicate
- 04-03-2008, 09:09 AM #1
Member
- Join Date
- Mar 2008
- Posts
- 8
- Rep Power
- 0
random string are duplicate
I create mathod random() for random a string.
When run this code below sometimes word at random are duplicate as:
word: ANT
word: ANT
I require random word and not duplicate.
How to solve this problem?
Java Code:class Test{ static String[] STRING = {"ANT","COW","HAM","BAT","DOG","CAT","MIN","MAX","JOB","CAR","WIN"}; static final Random random = new Random(); // // random(STRING); public static void random(String[] STRING){ for (int i = 0; i < 1;i++) { num = random.nextInt(STRING.length); System.out.println("random value: "+num); System.out.println("word : "+STRING[num]); } } }
- 04-03-2008, 09:43 AM #2
Java Code:import java.util.*; public class Test { static String[] STRING = { "ANT","COW","HAM","BAT","DOG","CAT","MIN","MAX","JOB","CAR","WIN" }; static final Random random = new Random(); public static void main(String[] args) { int[] nums = new int[6]; Arrays.fill(nums, -1); for (int i = 0; i < nums.length; i++) { int num = getNumber(nums); nums[i] = num; System.out.println("random value: "+num); System.out.println("word : "+STRING[num]); } } private static int getNumber(int[] array) { int n; do { n = random.nextInt(STRING.length); } while(contains(array, n)); return n; } private static boolean contains(int[] array, int n) { for(int i = 0; i < array.length; i++) { if(array[i] == n) return true; } return false; } }
- 04-03-2008, 09:53 AM #3
Member
- Join Date
- Mar 2008
- Posts
- 8
- Rep Power
- 0
Thank you very much.
- 04-03-2008, 10:01 AM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
It can be happened according to your code. In your for loop, after firing the first turn. It print a String and exit from it. Say first time you got the String "ANT". When you call the random() method next time, there is no way to keep the previous output. So even in the next time, you can get the same String there.
Similar Threads
-
[SOLVED] Get a random String
By LeoCoderIV in forum New To JavaReplies: 6Last Post: 04-07-2008, 02:58 PM -
How to make a hashmap to allow duplicate values?
By Preethi in forum New To JavaReplies: 0Last Post: 02-08-2008, 12:35 PM -
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01-17-2008, 10:44 PM -
How to prevent duplicate username entry in database?
By anki1234 in forum JavaServer Pages (JSP) and JSTLReplies: 4Last Post: 01-09-2008, 08:02 AM -
Duplicate entry in registration form!!!
By anki1234 in forum Advanced JavaReplies: 1Last Post: 01-04-2008, 08:15 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks