我已经坚持了一段时间了,我似乎无法让它发挥作用。我希望我的程序能够从“单词”数组中选择一个随机单词(用户先前添加的数组内容),然后允许用户输入另一个单词,看看它是否与程序选择的随机选择单词相匹配数组。如果单词匹配,则将输出消息,但如果不输出也将输出消息,但系统应向用户指示他们输入的任何字母是否在随机字符串中。我知道这是相当多的,但我已经被困了多年哈哈,谢谢! 这是我一直在使用的代码的一部分,有点简化。
private void btnGuess_Click(object sender,EventArgs e) {
string guess = txtGuess.Text;
string[] words = new string[6];
lstWords.Items.Add(txtEnterWord.Text);
Random rand = new Random();
for (int i = 0; i < words.Length; i++)
{
words[i] = rand.ToString();
}
if (String.Equals(guess, rand))
{
MessageBox.Show("Congratulations you have won! Your words are a match");
}
else
{
MessageBox.Show("Sorry but your words are not a match, try again");
}
}
答案 0 :(得分:0)
你必须
使用实际字词
words
数组
有一种方法从words
数组
如下:
private void btnGuess_Click(object sender, EventArgs e)
{
string guess = txtGuess.Text;
string[] words = new string[6] { "word1", "word2", "word3", "word4", "word5", "word6" }; //<--| initialize words array
lstWords.Items.Add(txtEnterWord.Text); //<--| what is that for?
string randWord = GetRandomWord(words); //<--| get rabdom word from words array
if (String.Equals(guess, randWord))
{
MessageBox.Show("Congratulations you have won! Your words are a match");
}
else
{
MessageBox.Show("Sorry but your words are not a match, try again");
}
}
static private string GetRandomWord(string[] words)
{
Random rnd = new Random();
return words[rnd.Next(0, words.Length)].ToString();
}
答案 1 :(得分:0)
Random rand = new Random()
for (int i = 0; i < words.Length; i++)
{
words[i] = rand.ToString();
}
在此循环中,您将rand.ToString()的输出分配给数组中的每个元素。如果你在循环之后查看数组,那么每个元素都将是&#34; System.Random&#34;因为在Random类型的对象上调用ToString方法会返回对象的类型,作为字符串。
创建新的Random对象时,您需要创建一个对象。一个可以返回随机数的对象。您没有创建随机数。
您想要从阵列中挑选其中一个字符串,这就是您可以解决的问题。
string thirdWordFromMyArrayOfWords = words[3];
使用Random获取一个随机数,该数字将在您的单词元素范围内:
int randomNumberWithinTheRangeOfMyArray = rand.Next(0,words.Length-1)
你需要减去一个,因为数组有6个元素(words.Length = 6),但它开始计数为零0,1,2,3,4,5所以如果你试图引用单词[6]你&# 39; ll抛出异常。
int randomNumberWithinTheRangeOfMyArray = rand.Next(0,words.Length-1);
string randomWordFromArray = words[randomNumberWithinTheRangeOfMyArray];
if (String.Equals(guess, randomWordFromArray))
可以进一步浓缩
if (String.Equals(guess, words[rand.Next(0,words.Length-1)]))
要考虑的其他事情是,因为每次点击按钮时都要求新的随机数,所以你会得到一个新的随机数,因此会从数组中得到一个新的随机字。
答案 2 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
namespace RandomWords
{
class Program
{
static void Main(string[] args)
{
string[] words = new[] { "csharp", "Stack", "overflow", "microsoft", "word5", "Coding"};
Random rnum = new Random();
string input = null;
while ( input != "end") {
int intnum = rnum.Next(0, words.Length);
Console.WriteLine("Guess a word or enter end to exit");
input = Console.ReadLine();
List<string> l = words.Where(x => x == input).ToList<string>();
if (l.Count != 0) { Console.WriteLine("Congratulations you have won! Your words are a match"); } else { Console.WriteLine("Sorry but your words are not a match, try again"); }
}
}
}
}