I would like to generate 6 numbers inside an array and at the same time, having it compared so it will not be the same or no repeating numbers. For example, I want to generate 1-2-3-4-5-6 in any order, and most importantly without repeating. So what I thought is to compare current array in generated array one by one and if the number repeats, it will re-run the method and randomize a number again so it will avoid repeating of numbers.
Here is my code:
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int Array[] = new int [6];
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen();
for(int loop = 0; loop <6 ; loop++)
{
if(Array[index] == Array[loop])
{
Array[index] = numGen();
}
}
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen()
{
int random = (int)(1+Math.random()*6);
return random;
}
}
I've been thinking it for 2 hours and still cant generate 6 numbers without repeating. Hope my question will be answered.
Btw, Im new in codes so please I just want to compare it using for
loop or while
loop and if else
.
Use
List
instead of array andList#contains
to check if number is repeated.You have to check if the number already exist, you could easily do that by putting your numbers in a
List
, so you have access to the methodcontains
. If you insist on using an array then you could make a loop which checks if the number is already in the array.Using ArrayList:
Using array:
And add this method somewhere as its used in the snippet above
You may use
java.util.Random
. And please specify if you want any random number or just the number 1,2,3,4,5,6. If you wish random numbers then , this is a basic code:if you don't understand the last for loop , please tell , i will update it.
Use List and .contains(Object obj) method. So you can verify if list has the random number add before.
update - based on time you can lost stuck in random loop.
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)
Here is the solution according to your code -
You just need to change the numGen method -
Complete code is -
you can use a boolean in a while loop to identify duplicates and regenerate