Home > Java > javaTutorial > body text

How to generate random numbers in Java

PHPz
Release: 2023-05-05 15:01:13
forward
1620 people have browsed it

1. Use Math.random() (generating a double between 0-1) method in j2se:

such as

public void numCreate(){   int array[] = new int[10];   for(int i=0;i<10;i++){   array[i]=(int)(Math.random()*100);        for(int j=0;j<i;j++){   if(array[i] == array[j]){   i--;   break;      }   }   }   for(int t=0;t<array.length;t++){   System.out.println(array[t]);   }   }
Copy after login

2. Use the Random object to generate random numbers, he Can generate random integers and floating point numbers. Use the next..() method of the Random instance. In general, choose the method without seeds to generate random numbers. Such as

public void numCreate(){   int array[] = new int[10];   for(int i=0;i<10;i++){   Random r = new Random();   array[i] = r.nextInt(100);   for(int j=0;j<i;j++){   if(array[i] == array[j]){   i--;   break;   }   }   }   for(int t=0;t<array.length;t++){   System.out.println(array[t]);   }   }
Copy after login

The parameters in the nextInt method can set the range of generated numbers. Between 0 (inclusive) and the specified value (exclusive).

The above is the detailed content of How to generate random numbers in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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!