calculator using radio buttons - c#

I'm trying to make a simple calculator using radio buttons in asp.net and c#. Two numbers are entered into a textbox each and a submit button is clicked and entered into a label.
The error I get is when the radio button is checked and submit is clicked, I get a runtime error; can anyone please help diagnose why?
This is my code:
int total;
if (rbAdd.Checked)
{
total = Convert.ToInt32(tbNo1.Text) + Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}
if (rbMult.Checked)
{
total = Convert.ToInt32(tbNo1.Text) * Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}

Simplified code that still fails the same way:
int total = 0;
int no1 = Convert.ToInt32(tbNo1.Text);
int no2 = Convert.ToInt32(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();

I've tried your code and I got error message(Input string was not in a correct format.) only whenever I enter non integer values, because of your convert code Convert.ToInt32(tbNo1.Text);.
Do you want the entered values to be only integer? If so, please try this code instead (Modified from John Saunders code):
int total = 0;
int no1 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo1.Text), 0));
int no2 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo2.Text), 0));
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
You also have to validate the entered values as well to protect invalid characters.
Otherwise if you don't need to convert the entered values to be integer you could use this code:
decimal total = 0;
decimal no1 = decimal.Parse(tbNo1.Text);
decimal no2 = decimal.Parse(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();

Related

Subtraction between multiple random input numbers

i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}

How to calculate weighted average grade for numbers between 1 and 5?

The user can input his grades for several lectures. The inputfield allows numbers and letters (because there are lectures that arent graded, however, the user should be able to note that he passed the lecture).
I want to calculate and display the user his weigthed average grade based on the credits a lecture gives. The numbers are doubles.
public void CalculateAverageGrade()
{
double gradeSum = 0;
double creditsSum = 0;
foreach (SemesterLecture semesterLecture in selectedSemester.semesterLectures)
{
try{
double grade = Double.Parse(semesterLecture.grade) * semesterLecture.lecture.credits;
gradeSum += grade;
creditsSum += semesterLecture.lecture.credits;
}
catch (Exception e){}
}
if (Double.IsNaN(Math.Round((gradeSum / creditsSum), 1, MidpointRounding.AwayFromZero)))
{
semesterGrade.text = "-";
}
else
{
semesterGrade.text = Math.Round((gradeSum / creditsSum), 1, MidpointRounding.AwayFromZero) + "";
}
}

c# Doing a sum of results of a search in a array

Ok so here's my problem. I have a vehicle constructor with several specs, and a class array that registers vehicles.
Within my form i wish to let the user search within that array for a specific value (in this case he shall input the type of vehicle and the year of the purchase, thus searching the array for them, and upon finding correspondents, he must then pick their price of acquisition and selling) and it shall return the sum of the profit.
Or in a simpler way: Profit = price of selling - price of acquisition.
The code I have thus far shows the profit individually and then the sum of the profits, how do I get just the latter?
int i;
bool found = false;
double lucro = 0;
for (i = 0; i < viaturas.NumElementos; i++)
if (viaturas.get(i).CVTipoVeículo == Int32.Parse(cbtipoveiculo.Text))
{
if (viaturas.get(i).CVDataVenda.Year == Int32.Parse(tbanopesquisa.Text))
{
double a = viaturas.get(i).CVPreçoVenda;
double b = viaturas.get(i).CVPreçoAquisição;
lucro += a - b;
found = true;
MessageBox.Show("O total de lucro das vendas em " + viaturas.get(i).CVDataVenda.Year + " foi de: " + lucro + "€", "Lucro", MessageBoxButtons.OK);
}
}
if (found == false)
{
MessageBox.Show("Conjunto de viaturas não existente!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
LimpaCampos();
}
If you want a value where you have all the profit summed then change your code to the following
int i;
bool found = false;
double lucro = 0;
for (i = 0; i < viaturas.NumElementos; i++)
if (viaturas.get(i).CVTipoVeículo == Int32.Parse(cbtipoveiculo.Text))
{
if (viaturas.get(i).CVDataVenda.Year == Int32.Parse(tbanopesquisa.Text))
{
double a = viaturas.get(i).CVPreçoVenda;
double b = viaturas.get(i).CVPreçoAquisição;
lucro += a - b; // Add it instead of overwriting
found = true;
//falta-me pô-lo a somar todos os lucros.
}
}
// Show a MessageBox here with a text (Sorry, I don't speak your language) that outputs your 'lucro' variable
If this is not what you meant, then I don't know how you can put all the profit into one value

Input String was not in a correct form

There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();
You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.
If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0
First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.
the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....
Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.

Calculate code to a new class.cs

i want to set my code to another class, example: A new class AgeCalculate.cs, How can I get the data from AgeCalculate.cs back to my Button_Click event.
Example:
AgeCalculate Calculate = new AgeCalculate();?
and from the class to Form1 =?
My code is now in button_Click.
double startkapital = 0;
double procentsats = 0;
int år = 0;
double kapital = 0;
startkapital = int.Parse(sKapTxt.Text);
procentsats = int.Parse(proSatsTxt.Text);
kapital = startkapital;
while (kapital < startkapital * 2)
{
kapital = kapital * (1 + procentsats / 100);
år = år + 1;
listBox1.Items.Add("Årtal: " + år);
listBox1.Items.Add("Kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
}
listBox1.Items.Add("Totalt antal år: " + år + "år ");
listBox1.Items.Add("Total kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
double exaktaåret = år / ((100 + procentsats) / 100);
listBox1.Items.Add(string.Format("Kapitalet fördubblades efter {0:0} år", exaktaåret));
if (kapital >= 2 * startkapital)
{
listBox1.Visible = true;
}
First, under your button_Click in your code behind C# event you will need to create an object of AgeCalculate.cs. I am not sure whether this is the correct way or not in C# but here it goes:
AgeCalculate calc = new AgeCalculate();
Then you use the object you created to call a function which returns the age calculated like this:
calc.FunctionName;
But before all, make sure in your class AgeCalculate there is a Function which has a return to return calculated age. And then once you do calc.FunctionName the calculated age will be returned.
Example:
In AgeCalculate.cs
public string calc(string value1)
{
//calculate age
String str = calculated age;
return str;
}
In C#
AgeCalculate calculate = new AgeCalculate();
calculate.calc(pass the argument you will use to calculate age);
You can create a public property in your AgeClass and get that property in your button click.

Categories

Resources