【问题标题】:Getting a value back from an array using a random method使用随机方法从数组中取回一个值
【发布时间】:2016-02-14 20:59:16
【问题描述】:

我在从我正在使用的随机方法中获取正确值时遇到问题。我的代码中的其他所有内容都有效,但是当我点击随机消息按钮时,我得到一个 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;
    }
}

【问题讨论】:

  • 我已经修改了很多方法,但仍然遇到相同的错误。我已经研究过这个问题,但到目前为止我所尝试的都没有奏效。您对我有任何进一步的反馈,为我指明正确的方向吗?

标签: java arrays random


【解决方案1】:

您必须设置属性的值tempSubjtempObjtempVerbtempAdjtempAdverb

请注意,您已经声明了这些属性,但您没有用任何值影响它们。因此,它们假定值为null

为了解决这个问题,您已经明确地为它们设置了一些值,或者调用了您已经创建的设置器。此外,您还必须修复您的设置器,因为它们没有正确设置您的属性:

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;
}

【讨论】:

  • 请注意,设置器已损坏,它们设置的是输入参数,而不是(隐藏的)成员变量。
  • 谢谢大家,让我再看看,看看我能不能解决这个问题。我以前使用过 setter 和 getter,但不是在这种情况下,所以我似乎需要更多的研究。我认为这与他们有关。我感谢 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2016-10-29
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多