计算机应用程序
编写一个能够加减乘除的计算机程序,窗体应用程序,并且能够处理可能产生的异常
程序代码:using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormTest
{
public partial class Form1 : Form
{
private double n1;
private double n2;
public Form1()
{
InitializeComponent();
this.n1 = 0;
this.n2 = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
this.Text = "Calculator";
this.comboBox1.Items.Add("+");
this.comboBox1.Items.Add("-");
this.comboBox1.Items.Add("x");
this.comboBox1.Items.Add("/");
this.comboBox1.SelectedIndex = 0;
this.label1.Text = "=";
this.button1.Text = "OK";
this.button2.Text = "Exit";
this.button3.Text = "Clear";
}
private void button1_Click(object sender, EventArgs e)
{
if (!txtValidate()) return;
double result = 0d;
if(this.comboBox1.SelectedIndex==0)
{
result = this.n1 + this.n2;
}
else if(this.comboBox1.SelectedIndex==1)
{
result = this.n1 - this.n2;
}
else if(this.comboBox1.SelectedIndex==2)
{
result = this.n1 * this.n2;
}
else
{
result = this.n1 / this.n2;
}
this.textBox3.Text = result.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox3.Clear();
this.comboBox1.SelectedIndex = 0;
}
private bool txtValidate()
{
try
{
this.n1 = double.Parse(this.textBox1.Text);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
return false;
}
try
{
this.n2 = double.Parse(this.textBox2.Text);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return false;
}
if(this.comboBox1.SelectedIndex==3&&double.Parse(this.textBox2.Text)==0d)
{
MessageBox.Show("Can't divide zero!");
return false;
}
return true;
}
}
}
