/*I am trying to generate 6 random unique (1-49) no.s and understand that my validation is incorrect.Help Please?*/

import java.util.*;
import javax.swing.JOptionPane;
public class ranUnique {


public static void main(String[] args) {

String output="";
int[] arrayRan=new int[6];int ran2;
for(int ran=0;ran<arrayRan.length;ran++){
arrayRan[ran]=(int)(Math.random()*50
//validate
for(ran2=0;ran2<=ran;ran2++){
if ((arrayRan[ran]==arrayRan[ran2]) || (arrayRan[ran]==0)) {
arrayRan[ran]=(int)(Math.random()...
//ran=ran-1;
}

}
}
Arrays.sort(arrayRan);
for(int sort=0;sort<arrayRan.length;sort++){
output=output+ arrayRan[sort]+" ";
}
JOptionPane.showMessageDialog(null,ou...
}
}

Here is "little dirty" solution

import java.util.*;
import javax.swing.JOptionPane;
public class RandomNumber
{	
	public static void main(String[] args) 
	{
	
		String output="";
		int[] arrayRan=new int[6];
		int rand;
		for(int i=0;i<arrayRan.length;i++)
		{
			do //execute following line
			{
				rand =(int)(Math.random()*48)+1;
			}while(doesExists(rand, arrayRan, i)); //while return is true
			arrayRan[i] = rand;
		}
		Arrays.sort(arrayRan);
		for(int i=0;i<arrayRan.length;i++)
		{
			System.out.println(arrayRan[i]);
		}
				
	}
	
	private static boolean doesExists(int rand, int[] arr, int i)
	{
		if( i != 0)
		{
			for(int j = 0; j < i; j++)
			{
				if(rand == arr[j])
					return true;	// number already in the array
			}			
		}
		return false;
	}
}

If you have any questions just ask

hey peter_budo,
thnx a lot for the 'dirty trick'...sounds good to me though....cheers buddy

Easiest way is take an arraylist and add first 50 no's. Shuffle it and take first 5 or 10. These 5 or 10 numbers will be unique random numbers... :)

  ArrayList<Integer> al2=new ArrayList<Integer>();
    for(int i=0;i<al.size();i++)
        al2.add(i);
    //shuffling array n taking first 5 values of array
    Collections.shuffle(al2);
    for(int j=0;j<5;j++)
    {           
     System.out.println(al2.get(j));
    }

    Enjoy
This question has already been answered. Start a new discussion instead.