使用随机方法从数组中获取值

时间:2016-02-14 20:59:17

标签: java arrays random

我遇到的问题是从我正在使用的随机方法中获取正确的值。我的代码中的其他所有内容都可以工作,但是当我点击随机消息按钮时,我得到一个null null null null null的输出,而不是每个数组的随机值。我的代码如下。任何帮助解决这个问题将不胜感激。

package shoutbox;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;

public class ShoutBox {

    String subj, obj, verB, adJ, adV, cannedM, randomM, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;

    private final String[] stringItems = {
        "I was sent here by the king to slay you!",
        "I will leave you to your slumber.",
        "I heard you have a piece of treasure I am interested in.",
        "I heard you know a way to save princess Layla from illness.",
        "Might I say you look lovely in the moonight.",
        "I love dragons!",
        "I will slay you and take your treasure!",
        "Are you a luck dragon?",
        "I think I will turn around and go home now.",
        "Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
    };

    private final String[] subject = {
        "I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
        "We", "The gold", "The book"
    };

    private final String[] object = {
        "sword", "treasure", "dragon", "cave", "head", "friends", "fire",
        "blood", "jewels", "magic"
    };
    private final String[] verb = {
        "yells", "hits", "torches", "sings", "laughs", "loves", "dances",
        "scouts", "hates", "wants"
    };
    private final String[] adjective = {
        "beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
        "hot", "scaly", "scary"
    };
    private final String[] adverb = {
        "quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
        "uneasily", "quickly", "abruptly"
    };

    public void setSubject(String tempSubj) {
        tempSubj = subj;
    }

    public void setObject(String tempObj) {
        tempObj = obj;
    }

    public void setVerb(String tempVerb) {
        tempVerb = verB;
    }

    public void setAdjective(String tempAdj) {
        tempAdj = adJ;
    }

    public void setAdverb(String tempAdverb) {
        tempAdverb = adV;
    }

    public String getSubject() {
        Random genSub = new Random();
        int randomSub = genSub.nextInt(subject.length);
        subj = subject[randomSub];
        return subj;
    }

    public String getObject() {
        Random genOb = new Random();
        int randomOb = genOb.nextInt(object.length);
        obj = object[randomOb];
        return obj;
    }

    public String getVerb() {
        Random genVerb = new Random();
        int randomVerb = genVerb.nextInt(verb.length);
        verB = subject[randomVerb];
        return verB;

    }

    public String getAdjective() {
        Random genAd = new Random();
        int randomAd = genAd.nextInt(adjective.length);
        adJ = adjective[randomAd];
        return adJ;
    }

    public String getAdverb() {
        Random genAdverb = new Random();
        int randomAdverb = genAdverb.nextInt(adverb.length);
        adV = subject[randomAdverb];
        return adV;
    }

    public ShoutBox() {

        JFrame frame = new JFrame();    //setting up Jframe components
        // Setting width, height, and title of window

        frame.setTitle("Shout Box");
        frame.setSize(450, 400);  // Size of frame window
        frame.setLocation(360, 200);  // Start location of frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);  // So you cannot resize frame

        JButton submitButton = new JButton("Submit");
        JButton randomButton = new JButton("Random Message");
        JLabel label = new JLabel("Pick a message and click submit or click random message");

        JList JlistMap;
        JTextArea textArearesult = new JTextArea(2, 21);
        textArearesult.setEditable(false);
        textArearesult.setLineWrap(true);
        textArearesult.setWrapStyleWord(true);

        JPanel panel = new JPanel();
        JLabel label1 = new JLabel("");
        label1.setForeground(Color.blue);
        JLabel label2 = new JLabel("         Your Message you have chosen is:         ");
        label2.setForeground(Color.red);
        JlistMap = new JList(stringItems);
        JlistMap.setVisibleRowCount(10);
        JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //add(new JScrollPane(JlistMap));  //Not working as of now
        panel.setBackground(Color.PINK);  // Pink background color

        frame.add(panel);
        panel.add(label);
        panel.add(JlistMap);
        panel.add(submitButton);
        panel.add(randomButton);
        panel.add(label2);
        panel.add(textArearesult);

        // Action Listener for the submit button to get the message that will display in the JTextArea
        submitButton.addActionListener((ActionEvent e) -> {
            textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
        });
        randomButton.addActionListener((ActionEvent e) -> {
            textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
        });

        // JList will get the selected Item and set the item to a string value t that will be set to cannedM
        JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
            JList list = (JList) e.getSource();
            String t = list.getSelectedValue().toString();
            cannedM = t;
        });

        frame.setVisible(true);  //set to be visible on panel
    }

    public String ShoutOutCannedMessage() {
        return cannedM;
    }

    public String ShoutOutRandomMessage() {
        randomM = tempSubj + " " + tempObj + " " + tempVerb + " " + tempAdj + " " + tempAdverb + ".";
        return randomM;
    }
}


    package shoutbox;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;

public class ShoutBox {

    String cannedM, randomM, subJ, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;

    private final String[] stringItems = {
        "I was sent here by the king to slay you!",
        "I will leave you to your slumber.",
        "I heard you have a piece of treasure I am interested in.",
        "I heard you know a way to save princess Layla from illness.",
        "Might I say you look lovely in the moonight.",
        "I love dragons!",
        "I will slay you and take your treasure!",
        "Are you a luck dragon?",
        "I think I will turn around and go home now.",
        "Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
    };

    private final String[] subject = {
        "I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
        "We", "The gold", "The book"
    };

    private final String[] object = {
        "sword", "treasure", "dragon", "cave", "head", "friends", "fire",
        "blood", "jewels", "magic"
    };
    private final String[] verb = {
        "yells", "hits", "torches", "sings", "laughs", "loves", "dances",
        "scouts", "hates", "wants"
    };
    private final String[] adjective = {
        "beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
        "hot", "scaly", "scary"
    };
    private final String[] adverb = {
        "quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
        "uneasily", "quickly", "abruptly"
    };

    public void setSubject() {
        Random genSub = new Random();
        int randomSub = genSub.nextInt(subject.length);
        tempSubj = subject[randomSub];
    }

    public void setObject() {
        Random genOb = new Random();
        int randomOb = genOb.nextInt(object.length);
        tempObj = object[randomOb];
    }

    public void setVerb() {
        Random genVerb = new Random();
        int randomVerb = genVerb.nextInt(verb.length);
        tempVerb = verb[randomVerb];
    }

    public void setAdjective() {
        Random genAd = new Random();
        int randomAd = genAd.nextInt(adjective.length);
        tempAdj = adjective[randomAd];
    }

    public void setAdverb() {
        Random genAdverb = new Random();
        int randomAdverb = genAdverb.nextInt(adverb.length);
        tempAdverb = subject[randomAdverb];
    }

    public String getSubject() {
        return tempSubj;
    }

    public String getObject() {
        return tempObj;
    }

    public String getVerb() {
        return tempVerb;    
    }

    public String getAdjective() {
        return tempAdj;
    }

    public String getAdverb() {
        return tempAdverb;
    }

    public ShoutBox() {

        JFrame frame = new JFrame();    //setting up Jframe components
        // Setting width, height, and title of window

        frame.setTitle("Shout Box");
        frame.setSize(450, 400);  // Size of frame window
        frame.setLocation(360, 200);  // Start location of frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);  // So you cannot resize frame

        JButton submitButton = new JButton("Submit");
        JButton randomButton = new JButton("Random Message");
        JLabel label = new JLabel("Pick a message and click submit or click random message");

        JList JlistMap;
        JTextArea textArearesult = new JTextArea(1, 30);
        textArearesult.setEditable(false);
        textArearesult.setLineWrap(true);
        textArearesult.setWrapStyleWord(true);

        JPanel panel = new JPanel();
        JLabel label1 = new JLabel("");
        label1.setForeground(Color.blue);
        JLabel label2 = new JLabel("         Your Message you have chosen is:         ");
        label2.setForeground(Color.red);
        JlistMap = new JList(stringItems);
        JlistMap.setVisibleRowCount(10);
        JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //add(new JScrollPane(JlistMap));  //Not working as of now
        panel.setBackground(Color.PINK);  // Pink background color

        frame.add(panel);
        panel.add(label);
        panel.add(JlistMap);
        panel.add(submitButton);
        panel.add(randomButton);
        panel.add(label2);
        panel.add(textArearesult);

        // Action Listener for the submit button to get the message that will display in the JTextArea
        submitButton.addActionListener((ActionEvent e) -> {
            textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
        });
        randomButton.addActionListener((ActionEvent e) -> {
            textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
        });

        // JList will get the selected Item and set the item to a string value t that will be set to cannedM
        JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
            JList list = (JList) e.getSource();
            String t = list.getSelectedValue().toString();
            cannedM = t;
        });

        frame.setVisible(true);  //set to be visible on panel
    }

    public String ShoutOutCannedMessage() {
        return cannedM;
    }

    public String ShoutOutRandomMessage() {
        randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
        return randomM;
    }
}

1 个答案:

答案 0 :(得分:0)

您必须设置属性tempSubjtempObjtempVerbtempAdjtempAdverb的值。

请注意,您已声明了这些属性,但您无法使用任何值对其进行影响。因此,他们假设值为null

为了解决这个问题,您可以明确地为它们设置一些值,或者调用它们已经创建的setter。您也可以修复您的setter,因为他们没有正确设置您的属性:

public void setSubject(String subj) {
    tempSubj = subj;
}

public void setObject(String obj) {
    tempObj = obj;
}

public void setVerb(String verb) {
    tempVerb = verb;
}

public void setAdjective(String adj) {
    tempAdj = adj;
}

public void setAdverb(String adv) {
    tempAdverb = adv;
}

修改

其他方法,就是使用你的getter,你有随机代码逻辑:

public String ShoutOutRandomMessage() {
    randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
    return randomM;
}