C#高手请进!有个关于数值类型问题?

编写一个程序,要求用户输入一个数值,然后判断是不是数值,请问高手们
这该如何写啊!

初学者
那么请问如何使用"正则表达"试来写这样的一个程序!

给一个简单的方法:
利用try语句来尝试将用户输入的内容转换为数字, 如果不发生异常, 那么用户输入的就是数字, 否则就不是.更科学的方法是利用正则表达式来验证.
下面的例子是利用TRY语句来将用户输入的内容转换为整型数字, 以判断是否为数字.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace isnumeric
{
/// <summary>
/// 用于判断用户输入的是否为数字。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(24, 16);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 0;
this.textBox1.Text = "textBox1";
//
// button1
//
this.button1.Location = new System.Drawing.Point(144, 16);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(392, 173);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{
string input = textBox1.Text; //接受用户输入
try //尝试将用户输入转化为整型数字
{
int a = Int32.Parse(input); //转化
MessageBox.Show("输入正确,你输入的是" + a.ToString()); //提示
}
catch //如果用户输入的不是数字(无法转化为整型数字)
{
MessageBox.Show("请输入一个数字!"); //提示信息
}
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2006-11-11
这种处理有时会出错,建议你用 正则表达试!
相似回答