Generate a random number without repeating numbers (JAVA)

Source: Internet
Author: User


public class Testrandom {

public static void Main (string[] args) {
Random number
int[] random = new int[4];
for (int i = 0; i < random.length; i++) {
Random[i] = (int) (Math.random () * 10);
for (Int J =0; J < I; J + +) {
if (random[j] = = Random[i]) {
i--;
Break
}
}
}

for (int i = 0; i < random.length; i++) {
System.out.print (Random[i]);
}
Analysis: To enter a random four-digit number is not too much difficulty, only need each random[i]= (int) (Math.random () *10); However, the resulting four-digit number is a certain probability of generating duplicate numbers, the code in the red number part will random[i] and the number generated before the comparison, if there is equal, i--, jump out of the loop, re-regenerated into a random[i], so reciprocating. Generates a random four-digit number without repeating numbers

Generate a random number without repeating numbers (JAVA)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.