-5

这是我的代码

我得到一串单词而不是一个单词,我认为我做得很好。如果你能给我一些很棒的建议,我包含所有代码的唯一原因是我可能看多了一些东西,我认为这与短语的构建有关,但我不确定

//import java libraries
import java.awt.*;
import javax.swing.*;
public class Emotion extends JFrame
{
    //set what you can use
    private JLabel label;
    private JLabel phrasem;

    public Emotion()
    {
        setLayout( new FlowLayout());

        //Wordlists
        String[] wordlistone =
        {
                "anger","misery"+"sadness"+"happiness"+"joy"+"fear"+"anticipation"+"surprise"+"shame"+"envy"+"indignation"+"courage"+    "pride"+"love"+"confusion"+"hope"+"respect"+"caution"+"pain"
        };

        //number of words in each list
        int onelength = wordlistone.length;

        //random number
        int rand1 = (int) (Math.random() * onelength);


        //building phrase
        String phrase = wordlistone[rand1];

        // printing phrase

        phrasem = new JLabel("PhraseOMatic says:");
        add (phrasem);

        label = new JLabel("Today you emotion is: " + phrase);
        add (label);

    }
    public static void main(String[] args)
    {
        Emotion gui = new Emotion();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(400, 100);
        gui.setVisible(true);
        gui.setTitle("My App (Alex Gadd)");

    }

}
4

4 回答 4

2

你有+你应该,在单词列表中的位置。
我想你只是把这两个弄错了。

String[] wordlistone = {
    "anger", "misery", "sadness", "happiness", "joy", "fear", "anticipation",
    "surprise", "shame", "envy", "indignation", "courage", "pride", "love",
    "confusion", "hope", "respect", "caution", "pain"
};

此外,您可以使用 java.util.Random 轻松获得随机 int,它比Math.random()

Random rand = new Random();

int i = rand.nextInt(wordlistone.length);
于 2013-08-03T14:27:58.287 回答
1

加号“+”运算符连接字符串,结果只有一个单词。初始化字符串数组时,使用逗号作为单词分隔符。

于 2013-08-03T14:30:22.457 回答
1

您的单词列表数组只有两个元素。您在第一个和第二个之间使用了逗号,然后意外地通过与其余单词连接创建了一个大字符串。改变这个:

    String[] wordlistone =
    {
            "anger","misery"+"sadness"+"happiness"+"joy"+"fear"+"anticipation"+"surprise"+"shame"+"envy"+"indignation"+"courage"+    "pride"+"love"+"confusion"+"hope"+"respect"+"caution"+"pain"
    };

对此

    String[] wordlistone =
    {
            "anger", "misery", "sadness", "happiness", "joy", "fear", "anticipation", "surprise", "shame", "envy", "indignation", "courage", "pride", "love", "confusion", "hope", "respect", "caution", "pain"
    };
于 2013-08-03T14:31:00.513 回答
1

两个观察:

  • array包含连接的String值,因此您应该替换+,
  • 您可能想在Random这里使用一个对象 -Math.random() * wordlistone.length行不通

这是我的版本:

String[] wordlistone = {
    "anger","misery","sadness","happiness","joy","fear","anticipation","surprise","shame","envy",
    "indignation","courage", "pride","love","confusion","hope","respect","caution","pain"           
};

Random r = new Random(); // you can reuse this - no need to initialize it every time
System.out.println(wordlistone[r.nextInt(wordlistone.length)]);
于 2013-08-03T14:33:48.133 回答