2014-04-28 16 views
0

我想在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(); 
     } 
    } 
} 
+1

你看到了什麼錯誤? – Nasir

+0

我們基本上可以做到「listBox1.Items.Add(article [randomarticle]);」並給我第一個沒有錯誤的單詞,但是我需要從每個數組中放出一個單詞來完成句子,當我嘗試添加第二個隨機單詞時,我會得到「NO Overload for method」添加2個參數「I我不確定是否需要使用佔位符我是新的列表框 – user3530547

+0

注意:不要創建這些獨立的randon生成器!它們都是相同的,因爲它們都是同時創建的,即具有相同的時間戳-seed!創建一個作爲靜態類變量! – TaW

回答

2
Listbox.Items.Add 

用不了3個參數

,你將需要使用的String.Format當您使用「{0} {1}」,你想將值添加到

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

,或者你也可以只做到這一點是這樣的:

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

如果我這樣做,它的作品完美。

+0

謝謝大家,只是另一個快速問題,如果我想讓程序生成10個句子而不是1個,那麼更容易複製該代碼10次,或者是否存在更優雅的方式來實現這一目標? – user3530547

0

您可以添加串值到列表框控件。所以,你應該增加你的句子是這樣的:

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