Hello , i am starting with java. I need to school make program that generates random numbers 1-20 , a than make method to check duplicates and replace them ... i find on the internet only methods with array or something like that , i cant use that because i dont know that... problem is i dont know how many numebrs it will be , i must enter how long it will be by user , and than check it ... numbers must be in field (array? im not sure with this word , im czech a[0],a[1] etc.)...
i need to do it with if,else,while,do ....

Recommended Answers

All 3 Replies

you will need an array anyway. how else are you going to check (in at least somewhat an efficient way) whether or not the number you just generated is a duplicate of one you've already found or not?
it's either an array or almost twenty extra variables: very inefficiënt and more (and messier) code.

public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int a[];
int n = 0;

do {
System.out.print("Zadej pocet prvku pole: ");
n = sc.nextInt();
} while(n <=0);

a = new int[n];


System.out.print("Generovaná čísla jsou: "); 
for (int i = 0; i < a.length; i++)
{
a[i] =(int)(Math.random()*20+1);
System.out.print(a[i]+ " ");
}

}}

i have this , generated numbers in a[n] array ... now i need to create method to check if they are some duplicates , if yes replace the duplicates

a few steps that should get you up and running pretty fast:
1. declare your array outside of your main method, so another method will can access it.
2. write a method that takes an int as parameter and iterates over the array to verify whether or not that int is already is in the array
3. IF NOT YET IN ARRAY: add the int to the next element of the array, and go to the next iteration
IF IT DOES EXIST IN THE ARRAY: generate a new int and re-check without going to the next iteration.

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.