Home > Java > JavaBase > body text

Java randomly generates non-repeating numbers between 1 and 15

王林
Release: 2019-12-05 13:33:05
Original
3696 people have browsed it

Java randomly generates non-repeating numbers between 1 and 15

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);
Copy after login

Generating an integer between 1 and 10 can be written as:

(int)(Math.random()*10 + 1);
Copy after login

And so on: to generate a number between 0~n, it should be written as:

Math.random()*n;
Copy after login

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));
        }
        
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!