Celsius to Fahrenheit Conversion Form - c#

I am trying to create a form that will convert Celsius to Fahrenheit and vice versa, but I am running into an error with the Conversion buttons code. The problem I am getting is that the variable convertedTemperature is left empty, so that should validation fail the message will be displayed via the ouput label(lblConvertedTemperature). But because of this being left blank I get the use of unassigned variable error. My question is how can I reword the processing section to not cause this error.
Double inputTemperature;// the variable that will store txtTemperatureInput for calculation
Double convertedTemperature;// the variable that will store the converted temperature
/*********************************
* INPUT *
* *******************************/
// when the user inputs a value and clicks calculate, the input must first be validated
if (Double.TryParse(txtTemperatureInput.Text, out inputTemperature) == false)
{
lblConvertedTemperature.Text = "Temperature must be a numeric value.";// message displayed in
//output label telling user their input was not accepted because it was not numeric
txtTemperatureInput.Focus();// sets the focus back onto the temperature textbox for a new entry
}
else
{
/*******************************
* PROCESSING *
*******************************/
if (optConvertToCelsius.Checked == true)// if the convert to celsius radio button is selected
// this statement will run
{
convertedTemperature = (inputTemperature - 32)*5 / 9;// the formula for converting
//Fahrenheit to Celsius
}
else if (optConvertToFahrenheit.Checked == true)// convert to fahrenheit was selected,
//meaning the convert to fahrenheit radio button was selected, so this statement will run
{
convertedTemperature = (inputTemperature * 9) / 5 + 32; ;// the formula for converting Celsius to
//Fahrenheit
}//end concatonated if
}//end if
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
}
}
}

My question is how can I reword the processing section to not cause this error.
Well, there are two situations that the compiler is concerned about:
If the input is invalid, you're already changing lblConvertedTemperature.Text anyway... so just return after you've done that. (You then don't need an else clause, which means you'll have less nesting - always nice for readability.)
Neither optConvertToCelsius nor optConvertToFahrenheit is checked. That's a situation the compiler considers, because you've got two separate conditions that you're checking. You may know it's never going to happen, of course.
For the latter, I'd suggest just removing the second condition:
if (optConvertToCelsius.Checked)
{
...
}
else
{
...
}
Note that I've removed the == true from the first condition just as a matter of style.
Now the compiler will know that if you get to this point, one of those two blocks will be executed. As both blocks assign to convertedTemperature, the variable will be definitely assigned at the end of that code.
EDIT: Just to clarify, if you have:
if (someCondition)
{
...
}
else if (someOtherCondition)
{
...
}
the compiler will not assume that one of those blocks will be executed, regardless of what the conditions are. Even if you know that exactly one condition will be true, the compiler just follows its relatively-simple rules.

You're scoping looks off. Simply move
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
To the "processing" scope.

Related

Using element position to print value stored in that position using a loop

I am creating this simple block of code that asks the user to fill an array, and then it asks the user to enter in the subscript value to print what value is in that position. What would I do to create a loop that asks the user what index element I am wanting to see and it prints what element is at the index position? For example I have this array of [1, 2, 3] and I enter in 0 it would return me the value 1. I hope you have the idea now.
Here's the code:
using System;
namespace Chapter_11
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[3]; // array initialization
for (int i = 1; i < 5; i++) // user input values
{
Console.Write("Enter in value {0}: ", i);
Console.ReadLine();
}
Console.Write("\n");
while (true)
{
Console.Write("Enter in a subscript value between 0 - 3 or 999 to quit: ");
string exit = Console.ReadLine();
if (exit == "999") // check string
{
break;
}
}
}
}
}
As I even see from your namespace, this looks like some sort of homework or maybe class lab work. You will really need to understand what is happening and why is happening otherwise every time, you will have to find someone to write the code for you.
(I would love to write this in comments section as it is not exactly an answer, but it would not fit there, and I feel this is even better for you than a ready answer)
I copied your code to console app and it is working. So that is good.
Let's look at closer what you are trying to do.
It seems everything is working as expected and if user press "999" it exits the code. So you are almost there. Check out the arrays from this link as it is a nice summary of what are arrays and how they work.
if (exit == "999") // check string
at this line, you are storing user entry to exit variable, as I would suggest to rename your variable to userInput as it will be more meaningful because it will not be only "exit", it will be holding the value of user entry.
So you basically grab the input from the user.
There are ways of checking conditions in C# and if-else statements are one of them.
You already check as if (exit == "999") if user entered "exit" code. What you can do is (And as a pseudo code )
Get user's entry // you already do that
Check if user wants to exit (you already do that with if (exit ==
"999") ) If not, than you can use Else statement which will
check if your If condition does not
satisfy as true.
Then in the else statement, whatever user entered, you can use it as an index of your array. (check Array index from here)
Again this code is not the best way to do it, but should get you going.

'else if' cant use variable from TryParse

double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
if (!double.tryParse(strx, out double a))
{MessageBox.Show("Incorrect input");}
else if (!double.tryParse(stry, out double b))
{MessageBox.Show("Incorrect input");}
x = a;
y = b; <---
The problem is that x and receive value of a, but y cant do the same for b.
I understand its because its within 'else' and might not get executed, but if I remove the else, then if both textboxes are empty or not numbers I'll get two error popups...
Any help resolving the issue?
You should question how your logic is set.
Right now, if either or both textboxes are wrong, the user sees the ambiguous "Incorrect input". I would find this frustrating. Where's the incorrect input? Is it the first text box? The second? Both?
As you develop better UIs, the answer will be to validate each text box and have each one that is wrong turn a color or provide some other feedback on the form itself. Otherwise, imagine how ugly the logic will get when you're presenting a form to the user with 20 different fields.
However, if you're only going to use two fields, and you want to have some logic, try something like this (note that in doing this, I got rid of the else, as well, so b will always be set):
double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
List<string>() invalids = new List<string>();
if (!double.tryParse(strx, out double a))
{invalids.Add("boxX");}
if (!double.tryParse(stry, out double b))
{invalids.Add("boxY")}
if invalids.Length != 0
{MessageBox.Show("Incorrect inputs in " + String.Join(", ", invalids.ToArray());}
x = a;
y = b;
The user will enjoy a single box that tells them of all the errors more than multiple pop-up boxes, or having to hit OK each time and see that there are more errors.
if (!double.TryParse(strx, out double a) || !double.TryParse(stry, out double b))
{
MessageBox.Show("Incorrect input");
return;
}

How to check if input in a float value has been left empty?

I'm creating a program which collects some personal info and persons' salary to calculate their earnings after tax.
I'm using a switch statement for the menu. Which looks like this:
Get a person’s details (p)
Get the Salary (s)
Calculate and display (d)
Exit (x)
I want the users to complete these in a sequential order, so before entering their salary or trying to calculate their pay, they are forced to enter their details. e.g.: Full name is the first personal detail that they have to fill in.
At this point the users has selected (d) to display their earnings, but they will be stopped because they haven't filled in their personal details.
Console.WriteLine("\nUser selected to calculate and display their earnings\n");
if (full_name == "")
{
Console.WriteLine("Error: Please enter personal details before attempting to display your pay\n");
break;
}
This works fine because it's a string, so if it has been left empty, they return to the original menu.
But I also want to stop them from trying to select option (d) if they haven't filled in option (s), their salary, which is stored in a float. If I try this:
if (annual_salary == null)
{break;}
it says that it will always be false since a value of type float is never equal to null of type float.
This is my while loop for option (s) which collects the data when the user selects this option.
while (valid == false)
{
Console.Write("Enter your annual salary: > ");
vtemp = Console.ReadLine();
// Validate the data entered
if (vtemp == "")
{
Console.WriteLine("\nError : Annual salary cannot be empty. Please try again...\n");
}
else
// Check if data is a valid integer
returnVal = float.TryParse(vtemp, out annual_salary);
if (returnVal == false)
{
Console.WriteLine("\nError : Please enter numbers only. Please try again...\n");
}
else
// Check value is positive
if (i < 0)
{
Console.WriteLine("\nError : Annual salary must be positive. Please try again...\n");
}
else
{
valid = true;
break;
}
}// End while
But if the users never select (s) and decide to go straight to (d) after filling in (p), They will get an incorrect value from the output.
So to clarify: How do I check if a float value has been left empty or skipped?
Simplest solution will be to give your s a default negative value, and make sure it's not negative before you continue.
Depending on how / where you're enforcing this, you can do different things. If you're doing a WPF or other GUI development, you can disable the button until it's all set.
If you want to do it in logic, you can go with the above solution, or have some flags that will be set to true when you select an option, and you will only continue if all flags are set to true, and so one.
Edit:
I've updated p to s. It's the same really. When he hits d either check that s is not negative (you can initialize it to -1), or if you go with the flag option, make sure the flag for it is true (it's set when you hit s for example).
Then, if you have all input, calculate, otherwise write a message saying he needs to input salary.

price textbox double

I wondering of anyone can help. I have a homework and a questien in it i dont understand what i need to look for to figuer out how to find it.
This is what i need to look for
Convert the contents of the price TextBox to a double and
validate the converted value so it is >= 0.0.
Call the GetDouble method from the InputUtility class,
with min value 0 and max value some big number.
Use a const declaration for the max.value
this is what im going to get in to my if before im going to tell its true
can enter the code two
private bool ReadAndValidatePrice(out double price)
{
if
{
price = txtPrice.Text;
return true;
}
else
{
MessageBox.Show("Enter Numbers Only", "Invalid Character", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPrice.Focus();
return false;
What i fink im going to do is if it is 0.0 or bigger it going to type it out. im i going to do like 0.0 > 999999
This is the best I can do with the little information you are presenting. You don't have to declare a double and save the converted data to it, but it makes it easier to read.
double converted;
converted = Convert.ToDouble(priceTB.text)
// Check if the converted data and if is less than 0, return out of the method
if(converted >= 0.0)
return;

Code to show a string of text

I'm in my first semester of college, and we're doing C#. I have to make a Winforms app that can convert between Celsius and Fahrenheit. I have all the code down (basically), but I need to have the result output to a label. I can send the answer to the label with lblOutput = Output.ToString(); but I need a message like "[input] Celsius will is [output] Fahrenheit". I tried putting in between the brackets after "ToString" but I was getting an error.
I have everything else coded except for this. I have been looking for the last couple days to figure it out, but I can't find an answer. Any help is greatly appreciated.
Edit:
The code that I have set up appears inside of a button. I have two radio buttons that saying that the value put into a text box is either Far -> Cels or Cels -> Far.
This is what I have coded in my button. If there is any way to improve upon it, please let me know.
private void btnConvert_Click(object sender, EventArgs e)
{
decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered
if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
{
decimal Output = ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius
txtOutput.Text = Output.ToString(); //Outputs the message to the user, showing the Celsius end point
}
else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
{
decimal Output = (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit
txtOutput.Text = Output.ToString(); //outputs the message to the user, showing the Farenheit end point
}
//txtOutput.Text = Output.ToString();
//Commented out because it gives an error saying that "Output does not exist in current context"
}
int fahrenheit, celsius;
// your code to set the two variables
string yourLabelText = String.Format("{0} Celcius is {1} Fahrenheit", celsius.ToString(), fahrenheit.ToString());
yourLabel.Text = yourLabelText;
Here is a reference for String.Format(). (thanks to Lukazoid!)
I don't know if you care about that, but for some cases you can get something like 12.243333333 by calling Output.ToString(), to make it more user-friendly, you can make it like this
Output.ToString("F2")
Which will change it to 12.24. You can use this together with string.Format like folks suggested.
I'm not sure what your question is about but if you need to format your output into a set phrase you can do this.
private void btnConvert_Click(object sender, EventArgs e)
{
decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered
// declare this outside the loop so you can use it later.
decimal output = 0M;
if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
{
output= ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius
}
else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
{
output= (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit
}
txtOutput.Text =string.Format("{0} Celsius will is {1} Fahrenheit",input,output);
}`
p.s. Do remember to use a try parse method to ensure that the txtInput is definitely convertible to decimal.
you can use string.format to replace tokens like {0} or {1} in a string, or you can directly use string concatenation. I'd like to avoid directly giving you the answer since you said this is homework, but if you look for c# examples of this you should be able to find your way.

Categories