简体   繁体   中英

How to get my random number generator to not give the same result every time? (So I dont have to restart the program)

How to get my random number generator (Java) to not give the same result every time? (So I dont have to restart the program) I have even tried to add in 2 different generators to see if that would change the outcome, but it dousnt. If anyone knows a meathod please let me know.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;


public class RNG {

    public static void main(String args[]) {

        //The frame
        JFrame frm = new JFrame();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setSize(500, 300);
        frm.setResizable(true);
        frm.setTitle("Random Number Generator");
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
        frm.setLayout(null);

        //The button
        JButton btn = new JButton("Refresh Number!");
        btn.setBounds(120, 100, 200, 50);
        frm.add(btn);

        //The generator
        int rand3;
        int min = 1;
        int max = 100;
        int rand2 = (int)(Math.random()*(max-min+1)+min);

        Random rand1 = new Random();
        rand3 = rand1.nextInt(1,100);


        //The actionlistener
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            System.out.println(rand3*rand2/100);

            }
        });
    }
    }

Your question is not clear, but if I understand right, you want to print random number from 1 to 100, just modify ActionPerformed method.

//The actionlistener
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        System.out.println(rand1.nextInt(100));

        }
    });

You get the same random number because you are calling method nextInt only one time in main method.

I think what your trying to do is print a new random number every time that the button is clicked. If that is the case consider the code below.

//The actionlistener
btn.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     System.out.println((int) (Math.random() * 100));

   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM