我创造了一个非常基本的魔术8球计划作为学习练习。 目前,每次单击按钮时,它都会输出0到9之间的随机数。 我现在想用一些小描述替换这些数字,例如“前景看起来不错”或“有一个很小的机会”等等。
我相信我需要在这里使用一个数组但不确定我需要什么样的数组以及代码需要嵌套的位置。
任何人都可以指出我正确的方向。
到目前为止代码......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Magic8ball
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 0;
private const int rangeNumberMax = 9;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Ask_Click(object sender, EventArgs e)
{
int rn = randomNumber;
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Please ask a question first", "No question was asked?");
}
else
{
MessageBox.Show("Number is" +" " + rn, "your answer...");
textBox1.Text="";
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
}
}
}
答案 0 :(得分:3)
属于该类的常规数组可能是要走的路。由于随机数从0开始,您可以将其用作数组索引messages[randomNumber]
;
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 0;
private const int rangeNumberMax = 9;
private readonly string[] messages =
{
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Yes",
};
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Ask_Click(object sender, EventArgs e)
{
int rn = randomNumber;
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Please ask a question first", "No question was asked?");
}
else
{
MessageBox.Show("Number is" +" " + rn, "your answer...");
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
textBox1.Text = messages[randomNumber];
}
}
}