Function description:
random()
method is used to return a random number, the range of random numbers is 0.0 =< Math .random < 1.0
.
For example:
Generating an integer between 0 and 9 is:
(int)(Math.random()*10);
Generating an integer between 1 and 10 can be written as:
(int)(Math.random()*10 + 1);
And so on: to generate a number between 0~n, it should be written as:
Math.random()*n;
Free learning video sharing: java course
The example is as follows:
package text; import java.util.ArrayList; import java.util.List; public class Text { public static void main(String[] args) { //创建一个Integer集合的链表 List<Integer> l = new ArrayList<Integer>(); //当链表中存在15个数时结束向链表中插入数据 while(l.size()<15){ int i = (int)(Math.random()*15+1); if(!l.contains(i)) l.add(i); } //迭代,输出链表中的元素 //for(int j:l) // System.out.println(j); for(int i=0;i<l.size();i++) { System.out.println(l.get(i)); } } }
Related article tutorial sharing: Java zero-based introduction
The above is the detailed content of Java randomly generates non-repeating numbers between 1 and 15. For more information, please follow other related articles on the PHP Chinese website!