简体   繁体   中英

How do I regenerate a random number in a different class in java?

I'm still pretty new to Java, so forgive me if my question seems obvious... I'm making a random insult generator, and all of its "vocabulary" of words it can use are in a class called generate(). I want to be able to change a randomly generated number from generate() in a method called randomize() in a different class called insultGenerator(). Here's me code for the insultGenerator() class:

import java.awt.Dimension;
import java.awt.event.*;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class insultGenerator {

    public static void main(String args[]){

        generate g = new generate();

        g.frame.setLayout(null);
        g.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Generate New Insult");
        button.setBounds(75, 100, 150, 40);
        button.addActionListener(new Action());
        g.frame.add(button);

        g.frame.setPreferredSize(new Dimension(300, 200));
        g.frame.setLocationRelativeTo(null);
        g.frame.pack();
        g.frame.setVisible(true);

        if(g.beginning == 0) {
            JLabel insult = new JLabel((g.beginningList[g.beginning] + g.secondList[g.second] + g.fourthList[g.fourth] + g.thirdList[g.third] + g.endingList[g.ending]),SwingConstants.CENTER);
            insult.setBounds(0, 38, 300, 25);
            g.frame.add(insult);
        } else {
            JLabel insult = new JLabel((g.beginningList[g.beginning] + g.firstList[g.first] + g.secondList[g.second] + g.fourthList[g.fourth] + g.thirdList[g.third] + g.endingList[g.ending]),SwingConstants.CENTER);
            insult.setBounds(0, 38, 300, 25);
            g.frame.add(insult);
        } 
    }

    static class Action extends generate implements ActionListener {
        generate g = new generate();
        public void actionPerformed(ActionEvent e) {
            //what happens when the button is clicked

            randomize();

            if(g.beginning == 0) {
                JLabel insult = new JLabel((g.beginningList[g.beginning] + g.secondList[g.second] + g.fourthList[g.fourth] + g.thirdList[g.third] + g.endingList[g.ending]),SwingConstants.CENTER);
                insult.setBounds(0, 38, 300, 25);
                g.frame.add(insult);
            } else {
                JLabel insult = new JLabel((g.beginningList[g.beginning] + g.firstList[g.first] + g.secondList[g.second] + g.fourthList[g.fourth] + g.thirdList[g.third] + g.endingList[g.ending]),SwingConstants.CENTER);
                insult.setBounds(0, 38, 300, 25);
                g.frame.add(insult);
            }
        }
    }

    public static void randomize() {
        //regenerate the random numbers in generate()

        generate g = new generate();

        g.beginning = g.begin.nextInt(2);
        g.first = g.one.nextInt(3);
        g.second = g.two.nextInt(5);
        g.third = g.three.nextInt(23);
        g.fourth = g.four.nextInt(14);
        g.ending = g.end.nextInt(3);

    }
}

and here's my code for the generate() class:

    import java.util.Random;

    import javax.swing.JFrame;
    public class generate {

        JFrame frame = new JFrame("Insult Generator");

        Random begin = new Random();
        int beginning = begin.nextInt(2);

        Random one = new Random();
        int first = one.nextInt(3);

        Random two = new Random();
        int second = two.nextInt(5);

        Random three = new Random();
        int third = three.nextInt(23);

        Random four = new Random();
        int fourth = four.nextInt(14);

        Random end = new Random();
        int ending = end.nextInt(3);

        String[] beginningList = {"You ", "Your "};
        String[] firstList = {"parents ", "friends ", "grandparents "};
        String[] secondList = {"are ", "smell ", "look ", "sound ", "act "};
        String[] thirdList = {"bad", "dumb", "ugly", "stupid", "fat", "terrible", "crappy", "poopy", "weird", "horrible", "atrocious", "awful", "gross", "substandard", "yucky", "unacceptable", "smelly", "rancid", "annoying", "disturbing", "creepy", "idiotic", "lame"};
        String[] fourthList = {"", "very ", "really ", "extremely ", "pretty ", "actually ", "quite ", "too ", "totally ", "strikingly ", "immensely ", "so ", "way too ", "kinda "};
        String[] endingList = {".", "!", "..."};
    }

Again, the problem is that the randomize() method isn't changing the values of the variables. Sorry if I gave more code than was necessary, but I figured it was better than not enough... Thanks in advance!

Your problem is, you are creating Generate object in every method and eventually it did not make any impact in your Generate object created in the main class. Try passing the Generate object created in the main method to Action class and randomize

Randomize - method

  public static void randomize(Generate g) {
    //reGenerate the random numbers in Generate()


    g.beginning = g.begin.nextInt(2);
    g.first = g.one.nextInt(3);
    g.second = g.two.nextInt(5);
    g.third = g.three.nextInt(23);
    g.fourth = g.four.nextInt(14);
    g.ending = g.end.nextInt(3);

}

Action

    static class Action extends Generate implements ActionListener {
    Generate g = null;
    public Action(Generate g) {
        this.g = g;
    } 
    ….
    …
   }

'Creation of Action from main`

button.addActionListener(new Action(g));

Yep, you're creating new instances of generate instead of working with the same object. You could pass g along as an argument, but placing declarations outside of the methods will give them more scope so they can be accessed outside of the methods (from your inner class). I had to do a project like this in a Java 201 course.

Plus remember the DRY principle: Don't Repeat Yourself. Meaning code snippets. See below, it still needs some refactoring/renaming but it solves the problem at hand and gets you in a better direction...

insultGenerator:

import java.awt.Dimension;
import java.awt.event.*;
// you're not using Random here
//import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class insultGenerator {
   // place the declarations of generate and insult here so that you can access in your inner class...
   static generate g;
   static JLabel insult;

   public static void main(String args[]) {
      // ...and create them here
      g = new generate();
      insult = new JLabel("", SwingConstants.CENTER);

      // put your gui initializations in one spot, and they only get called once instead of after each button fire
      g.frame.setLayout(null);
      g.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      g.frame.setPreferredSize(new Dimension(300, 200));
      g.frame.setLocationRelativeTo(null);
      g.frame.pack();
      g.frame.setVisible(true);

      insult.setBounds(0, 38, 300, 25);
      g.frame.add(insult);

      JButton button = new JButton("Generate New Insult");
      button.setBounds(75, 100, 150, 40);
      button.addActionListener(new Action());
      g.frame.add(button);

      // generate your first words
      button.doClick();
   }

   static class Action extends generate implements ActionListener {
      // here you were just creating a whole new g, NOT the same g that you are working with
      //generate g = new generate();

      public void actionPerformed(ActionEvent e) {
         // what happens when the button is clicked

         g.randomize();
         if(g.beginning == 0) {
            insult.setText(g.beginningList[g.beginning] + g.secondList[g.second] + g.fourthList[g.fourth]
                  + g.thirdList[g.third] + g.endingList[g.ending]);
         }
         else {
            insult.setText(g.beginningList[g.beginning] + g.firstList[g.first] + g.secondList[g.second]
                  + g.fourthList[g.fourth] + g.thirdList[g.third] + g.endingList[g.ending]);
         }
      }
   }
}

generate:

import java.util.Random;

import javax.swing.JFrame;

public class generate {
   // declare and initialize variables
   JFrame frame;
   int beginning = 0, first = 0, second = 0, third = 0, fourth = 0, ending = 0;

   String[] beginningList = { "You ", "Your " };
   String[] firstList = { "parents ", "friends ", "grandparents " };
   String[] secondList = { "are ", "smell ", "look ", "sound ", "act " };
   String[] thirdList = { "bad", "dumb", "ugly", "stupid", "fat", "terrible", "crappy", "poopy", "weird", "horrible",
         "atrocious", "awful", "gross", "substandard", "yucky", "unacceptable", "smelly", "rancid", "annoying",
         "disturbing", "creepy", "idiotic", "lame" };
   String[] fourthList = { "", "very ", "really ", "extremely ", "pretty ", "actually ", "quite ", "too ", "totally ",
         "strikingly ", "immensely ", "so ", "way too ", "kinda " };
   String[] endingList = { ".", "!", "..." };

   // create a constructor, it's good practice
   public generate() {
      frame = new JFrame("Insult Generator");
   }

   // Just call this method to generate new numbers/words.
   // Cleaned up unnecessary extra objects, just use the same instance of Random.
   public void randomize() {
      Random random = new Random();
      // automatically get the size, so when you add new words to the list you don't need to edit here
      beginning = random.nextInt(beginningList.length);
      first = random.nextInt(firstList.length);
      second = random.nextInt(secondList.length);
      third = random.nextInt(thirdList.length);
      fourth = random.nextInt(firstList.length);
      ending = random.nextInt(endingList.length);
   }
}

Off topic, but you may wish to tweak the width of your button, here's how it appeared to me on Linux: 按钮宽度不足会切断按钮文本

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