数字翻译成英文的小游戏

 
    其实这个也不算什么小游戏,只是初学 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 的。
而且显而易见,自动转换的方法既不受数字限制代码有简洁,使用也方便。
 
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值