使用数组创建随机Word / Phrase生成器

时间:2013-09-23 14:27:58

标签: arrays random

我有一个我想要使用的超过100个单词的列表,我已经在几个地方寻找解决方案,但由于我对xcode的了解有限,我不知道我将如何实现它们,生病了一个例子我在java中创建的应用程序,我想要在Xcode中(但有一个刷新按钮,我想我知道如何按钮)

//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[] wordlist =
    {
            "Anger","Misery","Sadness","Happiness","Joy","Fear","Anticipation","Surprise","Shame","Envy","Indignation","Courage","Pride","Love","Confusion","Hope","Respect","Caution","Pain","Rage Melon"
    };

        //number of words the list
        int length = wordlist.length;

        //random number
        int rand = (int) (Math.random() * length);


    //building phrase
    String phrase = wordlist[rand];

    // printing phrase
    phrasem = new JLabel("Today your emotion is:");
    add (phrasem);

    label = new JLabel(" " + phrase);
    add (label);

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

    }

}

1 个答案:

答案 0 :(得分:0)

尝试以下方法从数组中获取随机单词

NSArray *wordList = [NSArray arrayWithObjects:@"Anger",@"Misery",@"Sadness",@"Happiness",@"Joy",@"Fear",@"Anticipation", @"Surprise",@"Shame",@"Envy",@"Indignation",@"Courage",@"Pride",@"Love",@"Confusion",@"Hope",@"Respect",@"Caution",@"Pain",@"Rage Melon", nil];

int randomWord = (int)arc4random() % [wordList count];
NSLog(@"Random word = %@", [wordList objectAtIndex:randomWord]);