標籤:
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進行檢查。
這裡可以採用Regex的方法。
我們修改代碼如下:
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時才調用
語句,轉換純數字字串為整型變數。
總而言之,Regex是很強大的工具,在程式設計過程中我們應該加以善用。改天有機會,專門羅列一下Regex的用法(o´ω`o)ノ
軟體測試——C#判斷閏年的form小程式