I created a simple calculator to perform addition subraction multiplication and division. the problem in the code below is repeated code to get text from textField and parsing it into the int everytime a operation is performed. And I know there's way to do it in less lines of code so help me here.
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 formApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void nameLbl_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Submit_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void addBtn_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = num1 num2;
String sum = (total).ToString();
MessageBox.Show(sum);
}
private void firstNum_TextChanged(object sender, EventArgs e)
{
}
private void multBtn_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = num1 * num2;
MessageBox.Show(total.ToString());
}
private void subBtn_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = num1 - num2;
MessageBox.Show(total.ToString());
}
private void divideBtn_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = num1 / num2;
MessageBox.Show(total.ToString());
firstNum.Text = string.Empty;
secondNum.Text = string.Empty;
}
}
}
CodePudding user response:
Did you know you can link multiple buttons to the same event handler? See this answer to learn how.
Once you have all the buttons pointed at the same handler, you can use the same code, except the part that decides whether to add, multiple, divide, or subtract. For that you will need a series of if
statements, checking the sender
to see which button raised the event.
private void MyClickHandler(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = 0;
if (sender == addBtn) total = num1 num2;
if (sender == subBtn) total = num1 - num2;
if (sender == multBtn) total = num1 * num2;
if (sender == divideBtn) total = num1 / num2;
MessageBox.Show(total.ToString());
firstNum.Text = string.Empty;
secondNum.Text = string.Empty;
}
Extra credit
If you really want to be fancy you can get rid of the messy if
statements by using a lookup table with delegates for each operation.
private Dictionary<Control,Func<int,int,int>> _operations = new Dictionary<Control,Func<int,int,int>>
{
{ addBtn, (x,y) => x y },
{ subBtn, (x,y) => x - y },
{ multBtn, (x,y) => x * y },
{ divideBtn, (x,y) => x / y }
};
private void MyClickHandler(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 0;
String num = firstNum.Text;
String sNum = secondNum.Text;
if (num == "")
{
MessageBox.Show("error type both num");
}
else
{
num1 = int.Parse(num);
num2 = int.Parse(sNum);
}
int total = _operations[sender](num1,num2);
MessageBox.Show(total.ToString());
firstNum.Text = string.Empty;
secondNum.Text = string.Empty;
}
CodePudding user response:
The better way would be creating a string extension: Just create a static class in your code like below:
public static class Ext {
public static int ToInt(this string str) {
var x = 0;
if(int.TryParse(str, out x)) {
return x;
} else {
throw new Exception("Please enter only digits");
}
}
}
After you have this class you can easily do this:
int y = "125".ToInt();
or
string ss = "125";
int z = ss.ToInt();
or
int w = textBox1.Text.ToInt();
CodePudding user response:
how about taking it a bit further, create a private nested class to hold the user input values and use that class also to have a method that parse user input values and return a new instance of the user input class with the parsed values. We can also use enum
to distinguish the operators (addition, subtraction ..etc).
in the parent class Form1
we can add three methods. One for getting the parsed user input, and one to get the calculated result, and one to show the result for the user.
Link them together, and we will have a one method that would be used for each event to pass the enum
that we create, which will then do the calculation and shows the result to the user (or errors if any).
here is the example :
public partial class Form1 : Form
{
private enum CalculationType
{
Addition,
Subtraction,
Multiplication,
Division
}
private class UserInput
{
public int FirstNumber { get; set; }
public int SecondNumber { get; set; }
public UserInput() { }
public UserInput(int first, int second)
{
FirstNumber = first;
SecondNumber = second;
}
public static bool TryParse(string first, string second, out UserInput result)
{
UserInput = null;
if(int.TryParse(first, out int firstResult) && int.TryParse(second, out int secondResult))
{
UserInput = new UserInput(firstResult, secondResult);
return true;
}
return false;
}
}
private UserInput GetUserInput()
{
if(UserInput.TryParse(firstNum.Text, secondNum.Text, out UserInput result))
{
MessageBox.Show("error type both num");
}
else
{
return result;
}
return null;
}
private int GetResult(UserInput input, CalculationType type)
{
switch(type)
{
case CalculationType.Addition:
return input.FirstNumber input.SecondNumber;
case CalculationType.Subtraction:
return input.FirstNumber - input.SecondNumber;
case CalculationType.Multiplication:
return input.FirstNumber * input.SecondNumber;
case CalculationType.Division:
return input.FirstNumber / input.SecondNumber;
default:
return 0;
}
}
private void ShowResult(CalculationType type)
{
var userInput = GetUserInput();
if(userInput == null)
{
MessageBox.Show("error");
}
else
{
int total = GetResult(userInput, type);
MessageBox.Show(total.ToString());
}
}
private void addBtn_Click(object sender, EventArgs e)
{
ShowResult(CalculationType.Addition);
}
private void multBtn_Click(object sender, EventArgs e)
{
ShowResult(CalculationType.Multiplication);
}
private void subBtn_Click(object sender, EventArgs e)
{
ShowResult(CalculationType.Subtraction);
}
private void divideBtn_Click(object sender, EventArgs e)
{
ShowResult(CalculationType.Division);
}
}
UPDATE
Here is another simpler version where Func<UserInput, int>
is used directly.
public partial class Form1 : Form
{
private class UserInput
{
public int FirstNumber { get; set; }
public int SecondNumber { get; set; }
public UserInput() { }
public UserInput(int first, int second)
{
FirstNumber = first;
SecondNumber = second;
}
public static bool TryParse(string first, string second, out UserInput result)
{
result = null;
if (int.TryParse(first, out int firstResult) && int.TryParse(second, out int secondResult))
{
result = new UserInput(firstResult, secondResult);
return true;
}
return false;
}
public int Calculate(Func<UserInput, int> func)
{
return func.Invoke(this);
}
}
private void Calculate(Func<UserInput, int> func)
{
if (UserInput.TryParse(firstNum.Text, secondNum.Text, out UserInput result))
{
MessageBox.Show("error type both num");
}
else
{
int total = input.Calculate(func);
MessageBox.Show(total.ToString());
}
}
private void ShowResults()
{
Calculate(x => x.FirstNumber x.SecondNumber);
}
private void addBtn_Click(object sender, EventArgs e)
{
Calculate(x => x.FirstNumber x.SecondNumber);
}
private void multBtn_Click(object sender, EventArgs e)
{
Calculate(x => x.FirstNumber * x.SecondNumber);
}
private void subBtn_Click(object sender, EventArgs e)
{
Calculate(x => x.FirstNumber - x.SecondNumber);
}
private void divideBtn_Click(object sender, EventArgs e)
{
Calculate(x => x.FirstNumber / x.SecondNumber);
}
}