public class RandomDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<> ();
//产生7个不相同的数
ArrayList<Integer> list1 = getNum(list);
//遍历
for2(list1);
}
public static int random() {
int i = new Random().nextInt(34);
return i;
}
public static ArrayList<Integer> getNum(ArrayList<Integer> list) {
list.add(random());
for(int i = 0; i< list.size() ;i++) {
if(list.size() < 7) {
list.add(random());
if(list.get(list.size() - 1) == list.get(i)) { //新加入的 与原元素比较
list.remove(list.size() -1);
}
}
}
return list;
}
public static void for2(ArrayList<Integer> list) {
for(int i = 0; i < list.size() ;i++) {
System.out.print(list.get(i) + ", ");
}
}
}
|
|