package taskvip;

import java.util.Random;





public class Main {


   
    public static void main(String[] args)
    {
        int y =0;
        Random t =new Random ();
        fun1 e = new fun1();
      for ( e.i = t.nextInt(50); e.i < 100; e.i++)
        {
          
          
              e.A[e.i]= e.k.nextInt(50);
              y=e.k.nextInt();
             
        }
        for ( e.i = 0; e.i < 100; e.i++)
        {
        System.out.println("elements" + (e.i+1)+ "="+ e.A[e.i]);
       

        }
    

    }

}
package taskvip;

import java.util.Random;


public class fun1
{    public int i ;
     public int y ;
    public int []A = new int [100];
    Random k = new Random ();
       
}

how i can make random value "k" not repeat

Recommended Answers

All 7 Replies

You need to compare return from random function with some collection of previously provided numbers and check for duplicity. If a number already exists you want to call random function again, till you get number that does not exist in the collection.

but how i can insert that random value in "if" clause

i can now sit it in if condition, but that's still repeat my question how i can put that Random value "k" in array without repeat

This is how simple it goes

import java.util.ArrayList;

public class RandomNumber{
	
	public static void main(String[] args){
		int randomNumbers = 10;
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		int number = (int)(Math.random() * randomNumbers);
		numbers.add(number);
		for(int i = 0; i < randomNumbers-1; i++){
			do{
				number = (int)(Math.random() * 10);
			}while(numbers.indexOf(number)!=-1);
			numbers.add(number);
		}
		for(Integer i: numbers){
			System.out.println(i);
		}
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.