随机句子生成器/列表框输出

时间:2014-04-28 16:54:53

标签: c# arrays listbox

我正在尝试在C#中创建一个窗体,它将包含四个包含5个随机单词的数组。然后我将创建一个按钮,使用数组中的单词生成随机句子。现在我正在尝试将句子输出到列表框但我收到错误。将此信息输出到列表框的代码是什么?这是我的代码......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Chapter_16_Ex._16._4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGenerator_Click(object sender, EventArgs e)
        {
            string[] article = { "the", "a", "one", "some", "any", };
            string[] noun = { "boy", "girl", "dog", "town", "car", };
            string[] verb = { "drove", "jumped", "ran", "walked", "skipped", };
            string[] preposition = { "to", "from", "over", "under", "on", };

            Random rndarticle = new Random();
            Random rndnoun = new Random();
            Random rndverb = new Random();
            Random rndpreposition = new Random();

            int randomarticle = rndarticle.Next(article.Length);
            int randomnoun = rndnoun.Next(noun.Length);
            int randomverb = rndverb.Next(verb.Length);
            int randompreposition = rndpreposition.Next(preposition.Length);

            listBox1.Items.Add("{0} {1}",article[randomarticle],noun[randomnoun]);


        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

Listbox.Items.Add 

不带3个参数

当您使用“{0} {1}”并且想​​要为其添加值时,您将需要使用String.Format

listBox1.Items.Add(String.Format("{0} {1}", article[randomarticle], noun[randomnoun]));

或者您也可以这样做:

listBox1.Items.Add(article[randomarticle] + " " + noun[randomnoun]);

如果我这样做,它就会很完美。

答案 1 :(得分:0)

您可以将字符串值添加到列表框控件。所以你应该像这样添加你的句子:

listBox1.Items.Add(String.Format("{0} {1}", article[randomarticle], noun[randomnoun]));
相关问题