Multiplication in C# WPF - c#

I'm trying to make a program that generates 2 random numbers, then, after the user inputs the multiplication of those numbers, it will tell the user in a MessageBox whether or not the user was right or wrong. Sort of like an educational simulator.
I'm having problems with the end part. What I'm saying is; If the answer is the same as number1 and number2 multiplied, then it says; "Rétt!" and if not; "Rangt..."
Any ideas?
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
int answer = 0;
tbnumber1.Text = number1.ToString();
tbnumber2.Text = number2.ToString();
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
}
}
The full code.
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
tbsvar.Text = svar.ToString();
if (svar == (tala1 * tala2).ToString())
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}
}
}
SOLVED. Thank you to everyone who did/tried to help.
Final Version:
Final Version:
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}

To do this in a safe manner, you should not only Parse the text inputs to numbers, but you should also ensure that the text does in fact contain numbers first. If your numbers are supposed to be integers then you could use this:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
if (int.TryParse(tbnumber1.Text, out number1) ||
int.TryParse(tbnumber12.Text, out number2)) MessageBox.Show("Rangt...");
MessageBox.Show(svar == number1 * number2 ? "Rétt!" : "Rangt...");
}

You're putting the numbers in the textbox values. you have to convert textbox values to numbers.
private void btend_Click(object sender, RoutedEventArgs e)
{
try{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}catch{
MessageBox.Show("Invalid input");
}
}

You never define svar. You probably meant something like this, assuming svar was set earlier and is the correct product of the random multiplication:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
number1 = int.Parse(tbnumber1.Text);
number2 = int.Parse(tbnumber2.Text);
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}

1.I observed that you have not initialized variable 'svar' anywhere.
Initialise your svar variable with proper value.
2.Replace This :
if (svar == (number1 * number2).ToString())
With Following :
if (svar == (number1 * number2))

Related

How to divide two TextBoxes with a double and a int?

private void button1_Click(object sender, EventArgs e)
{
int res = 0;
try
{
res = Convert.ToInt32(costot.Text) / Convert.ToInt32(unidadesp.Text);
costou.Text = res.ToString();
}
catch (Exception ex) { }
}
Not sure if this is what you are after but it should give you the syntax.
private void button1_Click(object sender, EventArgs e)
{
int res = 0;
if (double.TryParse(costot.Text, out double costot) && double.TryParse(unidadesp.Text, out double unidadesp) && unidadesp != 0)
{
res = (int)(Math.Round(costot / unidadesp));
costou.Text = res.ToString();
}
}
If you need the costot and unidadesp both changed to Integers before the division then do this.
res = (int)(Math.Round(Math.Round(costot) / Math.Round(unidadesp)));
One more edit
private void button1_Click(object sender, EventArgs e)
{
if (double.TryParse(textBox1.Text, out double costot) && int.TryParse(textBox2.Text, out int unidadesp) && unidadesp != 0)
{
var res = costot / unidadesp;
textBox3.Text = res.ToString();
}
}

No syntax errors, but program does not produce any results

I have to create a program for class. My applications needs to have value returning methods for OilLubeCharges(), FlushCharges(), MiscCharges(), OtherCharges(), TaxCharges(), TotalCharges().
It needs to have void methods for ClearOilLube(), ClearFlushes(), ClearMisc(), ClearOther(), ClearFees().
Currently my code has no syntax errors, however when I compile it it does not calculate anything. The calculate, clear, and exit buttons also do not work. Any assistance as to why these issues are occurring would be appreciated. Below is my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CalcButton_Click(object sender, EventArgs e)
{
OilLubeCharges();
FlushCharges();
MiscCharges();
OtherCharges();
TaxCharges();
TotalCharges();
}
private void ClearButton_Click(object sender, EventArgs e)
{
oilCheckBox.Checked = false;
lubeCheckBox.Checked = false;
radFlushBox.Checked = false;
tranFlushBox.Checked = false;
insCheckBox.Checked = false;
mufCheckBox.Checked = false;
tireCheckBox.Checked = false;
partsTextBox.Text = "";
laborTextBox.Text = "";
serLabTotalTextBox.Text = "";
partsTotalTextBox.Text = "";
taxPartsTextBox.Text = "";
totalFeesTextBox.Text = "";
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private int OilLubeCharges()
{
int total = 0;
if (oilCheckBox.Checked)
{
total += 26;
serLabTotalTextBox.Text = total.ToString("c");
}
if (lubeCheckBox.Checked)
{
total += 18;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int FlushCharges()
{
int total = 0;
if (radFlushBox.Checked)
{
total += 30;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tranFlushBox.Checked)
{
total += 80;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int MiscCharges()
{
int total = 0;
if (insCheckBox.Checked)
{
total += 15;
serLabTotalTextBox.Text = total.ToString("c");
}
if (mufCheckBox.Checked)
{
total += 100;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tireCheckBox.Checked)
{
total += 20;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int OtherCharges()
{
int total = 0;
int parts = 0;
int labor = 0;
if (int.TryParse(partsTextBox.Text, out parts))
{
partsTextBox.Text = parts.ToString("c");
total = parts;
}
if (int.TryParse(laborTextBox.Text, out labor))
{
laborTextBox.Text = labor.ToString("c");
return total;
}
else
{
return total;
}
}
private decimal TaxCharges()
{
decimal parts = 0;
decimal partsTax;
partsTax = parts * .06m;
taxPartsTextBox.Text = partsTax.ToString("c");
return partsTax;
}
private decimal TotalCharges()
{
decimal total = 0;
total = OilLubeCharges() + FlushCharges() + MiscCharges() + TaxCharges() + OtherCharges();
totalFeesTextBox.Text = total.ToString("c");
return total;
}
}
As stated in the comments above, most likely your events are not hooked up to your buttons. You can do this several ways; typically it's done in the designer.
To know for sure if this is the cause, try this:
public Form1()
{
InitializeComponent();
CalcButton.Click += CalcButton_Click;
}
Note that this assumes your button is named "CalcButton". You can see whether that's true in the designer as well.
If that works, you need to do the same with the rest of your buttons either the same way or by selecting the method in the designer for the button.

C# Calculator using List Array error at some operations Windows Form Application

Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}

freezing form after clicking button

I have a problem regarding to payment button.
I don't encounter an error before building, but after building and clicking the payment button it hangs. I think its because of lblTotalPrice.text, but I don't know how to fix it.
public partial class Form1 : Form
{
int totalCost;
public double holDer;
public Form1()
{
InitializeComponent();
this.cbo1.Items.AddRange(new object[] { "Lechon Kawali - 200", "Bicol Express - 300"
,"Adobo - 350" });
}
private void btnAdd_Click(object sender, EventArgs e)
{
lb1.Items.Add(cbo1.SelectedItem);
lb1.SelectedIndex = lb1.SelectedIndex ;
int z = 0;
if (cbo1.SelectedIndex == 0)
{
z = z + 1;
}
if (cbo1.SelectedIndex == 1)
{
z = z + 2;
}
if (cbo1.SelectedIndex == 2)
{
z = z + 3;
}
switch(z)
{
case 1:
totalCost = totalCost + 200;
break;
case 2:
totalCost = totalCost + 300;
break;
case 3:
totalCost = totalCost + 350;
break;
}
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int deleteCost = 0;
int itemCost = 0;
foreach (int selectedIndex in lb1.SelectedIndices)
{
itemCost = int.Parse(lb1.Items[selectedIndex].ToString().Split('-')[1]);
deleteCost += itemCost; lb1.Items.RemoveAt(selectedIndex);
}
totalCost = totalCost - deleteCost;
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
lb1.Items.Remove(lb1.SelectedItem);
if (lb1.Items.Count > 0)
{
lb1.SelectedIndex = 0;
}
else
MessageBox.Show("No orders");
}
private void lblVAT_TextChanged(object sender, EventArgs e)
{
Add();
}
private void lblSubTotalCost_TextChanged(object sender, EventArgs e)
{
multiply();
Add();
}
public void multiply()
{
int a;
double b = 0.12;
bool Valid = int.TryParse(totalCost.ToString(), out a);
if (Valid)
lblVAT.Text = (a * b).ToString();
else
lblVAT.Text = "No VAT entered";
}
private void lbTotalPrice_TextChanged(object sender, EventArgs e)
{
Add();
}
public void Add()
{
int a;
int b;
bool AValid = int.TryParse(totalCost.ToString(), out a);
bool BValid = int.TryParse(lblVAT.Text, out b);
if (AValid && BValid)
{
lblTotalPrice.Text = ("Php " + (a + b).ToString());
}
}
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
}
As you stated in your comments, your problem it is not that your application hangs, but the problem is that you are getting a Input string was not in a correct format Exception.
That it seems is from this block:
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
As it is a not very complex code, your problem seems to be when you are casting your textboxes to Double. Be sure that you are using the correct separator for double values and that you not have any strange characters in tbPayment
Try using TryParse method:
double res;
if(double.TryParse(tbPayment.Text, out res))
{
holDer = res - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
else
{
MessageBox.Show("Input a correct format");
}
I suspect it's because the lblTotalPrice_TextChanged event-handler calls Add() which then changes the lblTotalPrice.Text property, causing the event to fire again, ad -infinitum?

Calculator using recursion

This is my code and i'm trying to do a basic calculator. Theres just one textbox where i'll be writing two numbers and adding them as well as getting the result in the same textbox like most calculators do.
my problem is that i get an error:
An unhandled exception of type 'System.StackOverflowException'
occurred in WindowsFormsApplication1.exe
after i press button + to write the next number.
public class calculator
{
int acum = 0;
int calcule(int option, int number)
{
switch (option)
{
case 3:
acum = acum + number;
break;
case 4:
acum = acum - number;
break;
case 5:
acum = acum * number;
break;
case 6:
acum = acum / number;
break;
default:
break;
}
if (number == 0)
{
return acum;
}
else
{
return calculate(option, number);
}
}
}
private void btnadd_Click(object sender, EventArgs e)
{
int numero1 = Convert.ToInt32(txtnumber.Text);
calculadora calcular = new calculadora();
txtnumber.Text = calculator.calculate(btnadd.TabIndex, number).ToString();
}
private void btnminus_Click(object sender, EventArgs e)
{
int numero1 = Convert.ToInt32(txtnumber.Text);
calculadora calcular = new calculadora();
txtnumber.Text = calculator.calculate(btnminus.TabIndex, number).ToString();
}
private void button1_Click(object sender, EventArgs e)
{
int number = Convert.ToInt32(txtnumber.Text);
calculadora calcular = new calculadora();
txtnumber.Text = calculator.calculate(button1.TabIndex, number).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
int numero1 = Convert.ToInt32(txtnumber.Text);
calculadora calcular = new calculadora();
txtnumber.Text = calculator.calculate(button2.TabIndex, number).ToString();
}
First of all, there is many problems in your code:
acum is not static, each time you do Calculator calc = new Calculator(); the value is set to zero. So even if there was no error in your code, the result would be number.
The value of the arg number never changes in Calculate method so there is no way you can escape the recursive call once you enter the else here (=> StackOverflowException)
if (number == 0)
{
return acum;
}
else
{
return calculate(option, number);
}
And also Calculate(...) is private... you cannot access it outside the class Calculator
Try this :
enum OperationEnum
{
ADD=3,
SUB=4,
MUL=5,
DIV=6
}
public class Calculator
{
public double Calculate(OperationEnum operation, params int[] operands)
{
if (operands == null)
throw new InvalidOperationException();
if (operands.Length == 0)
return 0;
if (operands.Length == 1)
return operands[0];
switch (operation)
{
case OperationEnum.ADD:
return Add(operands);
case OperationEnum.SUB:
return Subtract(operands);
case OperationEnum.MUL:
return Multiply(operands);
case OperationEnum.DIV:
return Divide(operands);
default:
throw new ArgumentException("operation");
}
}
private double Divide(int[] operands)
{
if (operands.Length == 0)
return 0;
var result = operands[0];
for (int i = 1; i < operands.Length; i++)
{
double divider = operands[i];
if (divider == 0)
{
throw new DivideByZeroException();
}
result /= divider;
}
return result;
}
private double Multiply(int[] operands)
{
if (operands.Length == 0)
return 0;
double result = operands[0];
for (int i = 1; i < operands.Length; i++)
{
result *= operands[i];
}
return result;
}
private double Subtract(int[] operands)
{
if (operands.Length == 0)
return 0;
var result = operands[0];
for (int i = 1; i < operands.Length; i++)
{
result -= operands[i];
}
return result;
}
private int Add(int[] operands)
{
return operands.Sum();
}
}
private double _accumulator = 0;
private void btnadd_Click(object sender, EventArgs e)
{
int numero1 = Convert.ToInt32(txtnumber.Text);
Calculator calcular = new Calculator();
_accumulator = calcular.Calculate(OperationEnum.ADD,_accumulator, number);
txtnumber.Text = _accumulator.ToString()
}

Categories

Resources