using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SoftwarTest_LeapYear
{
public partial class Form1 : Form
{
string yearStr = null;
int year = 0;
bool isLeapYear = false;
bool IsLeapYear(int year)
{
if (year % 400 == 0)
return true;
if (year % 4 == 0 && year % 100 != 0)
return true;
else
return false;
}
public Form1()
{
InitializeComponent();
}
private void But_judge_Click(object sender, EventArgs e)
{
text_output.Clear();
isLeapYear = IsLeapYear(year);
if (isLeapYear)
text_output.AppendText(yearStr.ToString() + " is a leap year:)");
else if (!isLeapYear)
text_output.AppendText(yearStr.ToString() + " is not a leap year:(");
else
text_output.AppendText("Please input a correct year!");
}
private void text_input_TextChanged(object sender, EventArgs e)
{
yearStr = this.text_input.Text;
year = int.Parse(yearStr);
}
private void text_output_TextChanged(object sender, EventArgs e)
{
}
}
}
但是经测试,如果输入非纯数字的字符串,Visual Studio会抛出exception。如下图:
现在我们来思考解决方法。
我们依旧调用Parse。
那么我们应该在传参之前对字符串yearStr进行检查。
这里可以采用正则表达式的方法。
我们修改代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace SoftwarTest_LeapYear
{
public partial class Form1 : Form
{
string yearStr = null;
int year = 0;
bool isLeapYear = false;
bool isYear = false;
public bool IsLeapYear(int year)
{
if (year % 400 == 0)
return true;
if (year % 4 == 0 && year % 100 != 0)
return true;
else
return false;
}
public bool IsYear(string yearStr)
{
Regex r = new Regex(@"^\d+$");
return r.IsMatch(yearStr);
}
public Form1()
{
InitializeComponent();
}
private void But_judge_Click(object sender, EventArgs e)
{
text_output.Clear();
isYear = IsYear(yearStr);
if (isYear)
{
year = int.Parse(yearStr);
isLeapYear = IsLeapYear(year);
if (isLeapYear)
text_output.AppendText(yearStr.ToString() + " is a leap year:)");
else
text_output.AppendText(yearStr.ToString() + " is not a leap year:(");
}
else
text_output.AppendText("Please input a correct year!");
}
private void text_input_TextChanged(object sender, EventArgs e)
{
yearStr = this.text_input.Text ;
}
private void text_output_TextChanged(object sender, EventArgs e)
{
}
}
}
我们利用函数IsYear判断输入内容是否为纯数字(为纯数字返回true,否则返回false)并返回结果到isYear这个布尔值中,并利用判断语句,只有当isYear值为true时才调用
语句,转换纯数字字符串为整型变量。
总而言之,正则表达式是很强大的工具,在程序设计过程中我们应该加以善用。改天有机会,专门罗列一下正则表达式的用法(o´ω`o)ノ
原文:http://www.cnblogs.com/baishusama/p/4401084.html