How to get random range number in set

后端 未结 3 1640
你的背包
你的背包 2021-01-21 12:26

I have 100 record [1 -> 100], i want get random 50 record in this, how to do in java? Thanks.

3条回答
  •  被撕碎了的回忆
    2021-01-21 13:05

    The only sure way to generate a four digit long unique code.

    I found was to first declare 4 integer variables, assign them random digits between 1 and 9 each.

    I then convert these integers into strings, join them together so that they form into a four digit long string and then I convert the resulting string into an integer.

    The resulting four digit random integer is stored in an array.

    "Please note!! that I am new to java"

    import javax.swing.JOptionPane;
    public class Rund4gen {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       // I begin by creating an array to store all my numbers
       String userInput = JOptionPane.showInputDialog("How many 4 digit long numbers would you like to generate?");
       int input = Integer.parseInt(userInput);
       // Now lets convert user input to a string
       int[] passCode = new int[input];
       // We need to loop as many time as the user specified
       for(int i = 0; i < input; i++){
           // Here I declare my integer variables
           int one, two, three, four;
           // For each of the integer variable I assign a rundom number
           one = (int)Math.floor((Math.random()*9)+1);
           two = (int)Math.floor((Math.random()*9)+1);
           three = (int)Math.floor((Math.random()*9)+1);
           four = (int)Math.floor((Math.random()*9)+1);
           // I need to convert my digits into a string in order to join them
           String n1 = String.valueOf(one);
           String n2 = String.valueOf(two);
           String n3 = String.valueOf(three);
           String n4 = String.valueOf(four);
           // Once conversion is complete then I join them as follows
           String nV = n1+n2+n3+n4;
           // Once joined, I then need to convert the joined result into an integer
           int nF = Integer.parseInt(nV);
           // I then store the result in an array as follows
           passCode[i] = nF;
       }
       // Now I need to print each value in the array
       for(int c = 0; c < passCode.length; c++){
           System.out.print(passCode[c]+"\n");
       }
       // Finally I thank the user for participating or not
       //JOptionPane.showMessageDialog(null,"Thank you for participating");
       System.exit(0);
    }
    

    }

提交回复
热议问题