一.问题描述
本周我们博客的主题是解决在写判断闰年程序时,如果输入了非数字的字符,如“aaaa”或者“&*()”等非法输入,因为c#中的int.Parse()函数处理这种情况时
会出现exception。我们的任务是避免出exception。
二.解决办法
我在网上搜索了int.Parse()这个函数的用法。得出了解决办法,那就是使用int.TryParse()这个函数
参考:http://www.cnblogs.com/fishtreeyu/archive/2011/01/15/1936193.html
int.TryParse(param1,out param2);
param1为要判断是不是int的字符串,param2为转换后的结果,如果param1是数字,那么param2就等于param1,否则param2为0;
int i = -1;
bool b = int.TryParse(null, out i);
执行完毕后,b等于false,i等于0,而不是等于-1,切记。
int i = -1;
bool b = int.TryParse("123", out i);
执行完毕后,b等于true,i等于123;
1、(int)是一种类型转换;当我们觟nt类型到long,float,double,decimal类型,可以使用隐式转换,但是当我们从long类型到int类型就需要使用显式转换,否则会产生编译错误。
2、int.Parse()是一种类容转换;表示将数字内容的字符串转为int类型。
如果字符串为空,则抛出ArgumentNullException异常;
如果字符串内容不是数字,则抛出FormatException异常;
如果字符串内容所表示数字超出int类型可表示的范围,则抛出OverflowException异常;
3、int.TryParse与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。
最后一个参数为输出值,如果转换失败,输出值为 0,如果转换成功,输出值为转换后的int值
4、Convert.ToInt32()是一种类容转换;但它不限于将字符串转为int类型,还可以是其它类型的参数;
比较:Convert.ToInt32 参数为 null 时,返回 0; int.Parse 参数为 null 时,抛出异常。Convert.ToInt32 参数为 "" 时,抛出异常; int.Parse 参数为 "" 时,抛出异常。 Convert.ToInt32 可以转换的类型较多; int.Parse 只能转换数字类型的字符串
三.代码
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 WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } public static Boolean CheckLeapYear(int year) { bool check = false; if (year % 4 == 0) check = true; if (year % 100 == 0) check = false; if (year % 400 == 0) check = true; return check; } private void button1_Click(object sender, EventArgs e) { string text; text = textBox1.Text; int result = 1; bool show=int.TryParse(text, out result); if (!show) { MessageBox.Show("您输入的不是数字!", "判断闰年结果"); } if (show) { if (CheckLeapYear(result)) MessageBox.Show(result+" 年是闰年", "判断闰年结果"); else { MessageBox.Show(result+" 年不是闰年", "判断闰年结果"); } } } } }
四.测试用例:
编号 | 测试用例 | 期望输出 | 原因 |
1 | 2015 | 不是闰年 | 不能被4整除 |
2 | 1996 | 是闰年 | 能被4整除不能被100整除 |
3 | 1700 | 不是闰年 | 能4和100整除,不能被400整除 |
4 | 2000 | 是闰年 | 能被4,100,400整除 |
5 | 啊啊啊啊 | 输入不是数字 | 不是数字 |
6 | %*& | 输入不是数字 | 不是数字 |
7 | abcd | 输入不是数字 | 不是数字 |
8 | 0100 | 不是闰年 | 能4和100整除,不能被400整除 |
五.测试结果:
(1) “2015”
(2) “1996”
(3) “1700”
(4)“2000”
(5)“啊啊啊啊”
(6)%*&
(7)“abcd”
(8)"0100"
六.测试心得:
小小的int.Parse()函数没用好就会报出异常,程序在编程时要注意每一个函数的用法,为测试时考虑。
尽量了解每个函数的输入,输出和一些特殊条件