其实这个也不算什么小游戏,只是初学
C#
,在阅读
C#2.0
完全参考手册的一个小范例程序时,一时感觉有趣并加上一点点的冲动,
将控制台输出的效果改了一下,并优化了一点其中的功能,制作成了
winform
显示输出的形式,效果类似于数字的英文翻译器。
首先定义:
string[] digits ={ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
此时,如果你想实现输入数字后立刻可以显示出对应的英文单词,则在
textBox
中写事件,代码如下:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
//textBox1
中输入数字,实现自动转换
if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) //
输入非数字将出现提示
{
MessageBox.Show("
只能输入数字
");
e.Handled = true; //
指示已经处理过
keypress
事件
}
else
{
for (int i = 48; i <= 57; i++)
if (e.KeyChar == i)
{
textBox2.Text += digits[i - 48].ToString() + " "; //textBox2
中显示结果
}
}
}
如果需要不想自动转换,而是输入数字后按某个按钮转换,则设置一个
button
,并写事件,代码如下:
private void button1_Click(object sender, EventArgs e) //
手动转换
{
int num;
int nextdigit;
int numdigits;
int[] n = new int[20];
String result = null;
nextdigit = 0;
numdigits = 0;
if (textBox1.Text != "")
{
num = Convert.ToInt32(textBox1.Text);
do
{
nextdigit = num % 10;
n[numdigits] = nextdigit;
numdigits++;
num /= 10;
} while (num > 0);
numdigits--;
for (; numdigits >= 0; numdigits--)
{
result = result + digits[n[numdigits]].ToString()+" ";
}
textBox2.Text = result.ToString() + "";
}
else
MessageBox.Show("
请输入转换数字!
");
}
}
上面单击
button
后翻译数字的方法有一个问题,就是在
textBox1
里输入的数字大小有限制,因为预设的是
Int32
的。
而且显而易见,自动转换的方法既不受数字限制代码有简洁,使用也方便。