国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase How to generate non-repeating random numbers in java

How to generate non-repeating random numbers in java

Dec 09, 2019 pm 02:48 PM
java

How to generate non-repeating random numbers in java

Generating random numbers in Java

1. Call the random() method in the Math class below java.lang to generate random numbers

Create a new file The file extension is java, and the file name is MyRandom. Write the following code in this class:

public class MyRandom {
public static void main(String[] args) {
int radom = (int)(Math.random()*10);
System.out.println(radom);
}
}

Among them, Math.random() //Generate a random decimal between 0 and 1.

To generate an integer between 0 and 9 is: (int)(Math.random()*10);

To generate an integer between 1 and 10 you can write: (int)(Math.random()*10 1);

And so on: to generate a number between 0 and n, it should be written as: Math.random()*n;

Get a random positive integer with a specified length:

public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
} for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}

2. Call the Random class below java.util. Instances of this class are used to generate a pseudo-random number stream and generate a random integer, then call The nextInt() method of this class
Before using the Random class, import java.util.Random under the package; the code is:

import java.util.Random;
public class MyRandom {
public static void main(String[] args) {
Random rand = new Random();
int rInt = rand.nextInt(10);
System.out.println(rInt);
}
}

where Random rand = new Random() is to create a New random number generator; rand.nextInt(int n) is a uniformly distributed int value between 0 (inclusive) and the specified value n (exclusive) taken from this random number generator's sequence.

In Java, in the specified integer range class, the loop generates different random numbers

The example of generating 6 different random integers within 20 is as follows:

public class MyRandom {
public static void main(String[] args) {
int n = 20;
Random rand = new Random();
boolean[] bool = new boolean[n];
int randInt = 0;
for(int i = 0; i < 6 ; i++) {
do {
randInt = rand.nextInt(n);
}while(bool[randInt]);
bool[randInt] = true;
System.out.println(randInt);
}
}
}

Use a Boolean variable array to store whether the number is generated. After generation, the number becomes true as the corresponding Boolean value in the table below the Boolean array. The next time the number is generated, it will enter the do...while loop again to generate numbers until a number that has not been generated before is generated.

For example: Generate an int type array with a length of 50, and insert numbers between 0-50 into it randomly, and they cannot be repeated.

The code is as follows:

public class MyRandom {
public static void main(String[] args) {
int[] intRandom = new int[50];
List mylist = new ArrayList(); //生成數(shù)據(jù)集,用來保存隨即生成數(shù),并用于判斷
Random rd = new Random();
while(mylist.size() < 50) {
int num = rd.nextInt(51);
if(!mylist.contains(num)) {
mylist.add(num); //往集合里面添加數(shù)據(jù)。
}
}
for(int i = 0;i <mylist.size();i++) {
intRandom[i] = (Integer)(mylist.get(i));
}
}
}
/**
* 隨機產(chǎn)生指定的范圍不重復的集合
* @param size
* @return
*/
public static Set<Integer> generateRandomArray(int size){
Set<Integer> set = new LinkedHashSet<Integer>(); //集合是沒有重復的值,LinkedHashSet是有順序不重復集合,HashSet則為無順序不重復集合
Integer num = size;
Integer range = size;
Random ran = new Random();
while(set.size() < num){
Integer tmp = ran.nextInt(range); //0-51之間隨機選一個數(shù)
set.add(tmp);//直接加入,當有重復值時,不會往里加入,直到set的長度為52才結(jié)束
}
return set;
}

For more java knowledge, please pay attention to the java basic tutorial column.

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

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles