C# Use of unassigned local variable [duplicate] - c#

This question already has answers here:
c# switch problem
(8 answers)
Closed 6 years ago.
I am trying to do make a basic program in C# that calculates netPay and grossPay, however I am running into a little problem. I included a switch to set my taxRate to a const based off of a letter provided, after I added the switch into my program it says taxRate is an unassigned local variable. I am still very new to C# so I probably made a very simple mistake but for the life of me I cant find it. thanks in advance for the help.
const int married = 15, single = 22, divorced = 23, widowed = 13;
double payRate, hoursWorked, grossPay, netPay;
double taxRate;
char marStatus;
Console.WriteLine("Please Enter Hourly Wages");
payRate = int.Parse(Console.ReadLine());
Console.WriteLine("Please Enter Hours Worked");
hoursWorked = int.Parse(Console.ReadLine());
Console.WriteLine("Please Enter Marital Status Letter: (M) Married (S) Single (D) Divorced (W) Widowed");
marStatus =Convert.ToChar(Console.ReadLine());
switch (marStatus)
{
case 'M':
taxRate = married;
break;
case 'S':
taxRate = single;
break;
case 'D':
taxRate = divorced;
break;
case 'W':
taxRate = widowed;
break;
default:
Console.WriteLine("Invalid Input, Please Try Again.");
break;
}
if (hoursWorked > 40)
{grossPay =((hoursWorked-40)*(payRate*1.5))+(40*payRate);}
else
{ grossPay = payRate * hoursWorked; }
netPay = grossPay * taxRate; // This is where I have the problem
Console.WriteLine("Gross Pay=" +grossPay);
Console.WriteLine("Net Pay=" +netPay);
Console.WriteLine("xxx");
Console.ReadLine();

in the switch-case, if the defual case is met (no other case matches "marStatus"), then taxRate doesn't get asigned with a value. later you try to use this variable, with no value. this is the compilation error you're getting. asign a value to the variable.

Related

Why do I need a double? [duplicate]

This question already has answers here:
C# short/long/int literal format?
(5 answers)
Closed 2 years ago.
Simply put, I'm very new and I do not understand why I need total to be a double, my teacher put it as a float in his program, but it doesn't work for me.
int choix;
double total = 0;
do
{
Console.WriteLine("Menu\n\n");
Console.WriteLine("1 - Pizza 3.25$\n");
Console.WriteLine("2 - Poutine 2.75$\n");
Console.WriteLine("3 - Liqueur 1.25$\n");
Console.WriteLine("4 - Fin\n\n");
Console.WriteLine("Votre choix(1 - 4)");
choix = int.Parse(Console.ReadLine());
switch(choix)
{
case 1:total = total + 3.25;
break;
case 2:total = total + 2.75;
break;
case 3:total = total + 1.25;
break;
case 4:Console.WriteLine("Voici le total " + total);
break;
default:Console.WriteLine("Erreur de choix");
break;
}
}
while (choix != 4);
Sorry for this dumb question, but I cannot find answers anywhere.
Basically because of how c# interprets the code, c# doesnt know whether your decimal numbers will overflow or not, so it automatically assign all floating values as a double (which can actually hold more values than a float). So what you need to do in order to the compiler understand that you actually want a float, is to add an f at the end of the numbers.
int choix;
float total = 0;
do
{
Console.WriteLine("Menu\n\n");
Console.WriteLine("1 - Pizza 3.25$\n");
Console.WriteLine("2 - Poutine 2.75$\n");
Console.WriteLine("3 - Liqueur 1.25$\n");
Console.WriteLine("4 - Fin\n\n");
Console.WriteLine("Votre choix(1 - 4)");
choix = int.Parse(Console.ReadLine());
switch (choix)
{
case 1:
total = total + 3.25f;
break;
case 2:
total = total + 2.75f;
break;
case 3:
total = total + 1.25f;
break;
case 4:
Console.WriteLine("Voici le total " + total);
break;
default:
Console.WriteLine("Erreur de choix");
break;
}
}
while (choix != 4);

I'm trying to make a calculator but I keep getting CS0165 and I'm confused as to why

The Console.Writeline(result); at the end returns error CS0165 Use of unassigned local variable 'result' and I don't know why. Would appreciate an explanation as I'm a complete beginner. Like I said in the title, I'm trying to build a calculator.
char Operator;
double firstNumber;
double secondNumber;
Console.WriteLine("Enter the first number");
string firstNumberAsText = Console.ReadLine();
Console.WriteLine("Enter the second number");
string secondNumberAsText = Console.ReadLine();
Console.WriteLine(#"Enter a math operation. '+' for addition, '-' for subtraction, '*' for multiplication, '/' for division, '%' for remainder and '^' for power");
string mathOperator = Console.ReadLine();
firstNumber = Convert.ToDouble(firstNumberAsText);
secondNumber = Convert.ToDouble(secondNumberAsText);
Operator = Convert.ToChar(mathOperator);
double result;
switch (Operator)
{
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
result = firstNumber / secondNumber;
break;
case '%':
result = firstNumber % secondNumber;
break;
case '^':
result = Math.Pow(firstNumber, secondNumber);
break;
default:
Console.WriteLine("unrecognised operator: " + Operator);
break;
}
Console.WriteLine(result);
Console.ReadKey();
The error itself tells you what's wrong:
Error CS0165: Use of unassigned local variable 'result'
This means that you're trying to use a variable that may not have been initialized yet. Notice that it isn't initialized it when it's declared, and it isn't assigned a value in the default: case in the switch statement.
So there are two ways to solve this:
1) Initialize the variable when you declare it
double result = 0;
2) Or, make sure every possible code path (including then default switch case) assigns a value to it before it's used
default:
result = 0;
Console.WriteLine($"unrecognised operator: {Operator}");
break;
In the case of an unrecognised operator, the result variable would be undefined when trying to do the Console.WriteLine(). You either need to set it to a value when catching the default behaviour, or initialize it before the switch.

Float/Double type input validation in C#

This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
TryParse is your good friend here. In most scenarios, you should favor using TryParse than Parse. In your example, you can do something like:
int validInt;
int.TryParse(Console.ReadLine(), out validInt);
float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);
Parse vs. TryParse
The easiest way, IMHO, to change the routine is to rewrite Parse into corresponding TryParse:
// UserChoice = int.Parse(Console.ReadLine());
UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;
...
A bit more complex (you have to convert float into float?)
// FahrenheitInput = float.Parse(Console.ReadLine());
float v;
FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;
The same scheme for CelsiusInput
// CelsiusInput = double.Parse(Console.ReadLine());
double d;
CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;
The underlying mechanic of the code is
We try to parse user input TryParse(Console.ReadLine()...
If parse succeeds (and thus TryParse returns true) we just return the out (parsed value).
If parse fails (and thus TryParse returns false) we return some special a value (-1 for UserChoice or null in case of FahrenheitInput or CelsiusInput)
P.S. in the first switch you have just case 1, case 2 and case 5; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implement case 3 and case 4 in the switch or edit the error message.
Use int.TryParse instead of int.Parse and float.tryParse instead of float.Parse
While all the answers provided seem to work, the question you asked was
how can I prevent exceptions from being thrown [..]
and I just want to point out that you do this by putting the part which throws the exception in an try-catch-block. What this does is it executes the code within try until an exception is beeing thrown and then passes this exceptions as a parameter to the catch-part where you can handle it:
EXAMPLE
do
{
try
{
// the code you already have
}
catch (Exception ex)
{
Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
}
} while (UserChoice != 5);
Of course preventing exceptions from beeing thrown at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Using switch-case-statements for error-handling is quite common practice...

My Loop is not working - it exits before it should

I'm new to programming. I tried this code and the loop is not working. The console application just ends after one operation, and I would like to continue doing more until I choose to say "no." Where am I making a mistake here? I want the program to keep going until I say so. Thanks in advance.
static void Main(string[] args)
{
Console.WriteLine("Program to convert USA Dollars to five different currencies,");
Console.WriteLine();
double dollars, euros, turkisLira, yen, britishPounds, mexicanPeso;
char option;
euros = 0.72;
turkisLira = 2.09;
yen = 101.73;
britishPounds = 0.59;
mexicanPeso = 13.03;
string answer = "Y";
do
{
Console.Write("Enter the Amount of USA Dollars to Convert:");
dollars = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("1.Convert to Euros");
Console.WriteLine("2.Convert to Turkis Lira");
Console.WriteLine("3.Convert to Japanes Yen");
Console.WriteLine("4.Convert to British Pounds");
Console.WriteLine("5.Convert to Mexican Pesos");
Console.Write("Enter the option of Currency you wish to convert : ");
option = Convert.ToChar(Console.ReadLine());
switch (option)
{
case '1':
euros = dollars * euros;
Console.WriteLine("The amount of Euros given is : {0}", euros);
break;
case '2':
turkisLira = dollars * turkisLira;
Console.WriteLine("The amount of Turkis Liras given is : {0}", turkisLira);
break;
case '3':
yen = dollars * yen;
Console.WriteLine("The amount of Japanes Yen given is : {0}", yen);
break;
case '4':
britishPounds = dollars * britishPounds;
Console.WriteLine("The amount of British Pounds given is : {0}", britishPounds);
break;
case '5':
mexicanPeso = dollars * mexicanPeso;
Console.WriteLine("The amount of Mexican Pesos given is : {0}", mexicanPeso);
break;
}
Console.WriteLine(" Do you wish to do more conversions? (yes/no)");
answer = Console.ReadLine();
if (answer.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (answer.Equals("N"))
{
Console.WriteLine("No");
}
} while (answer.ToLower() == "y'");
Your requirement is
I will like to continue doing more until I choose to say No
while your exist condition is
(answer.ToLower() == "y'");
So, if somebody clicks anything other than y, the loop would exit. You would want the exist condition to be
(answer.ToLower() != "n'");-
I think you have miss type ' in "y'" where you just want receive "y" to continue.

System.FormatException in C#

I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong? I am supposed to make this console program as homework to learn about loops, but I am finding out more about other things. It is supposed to keep a running tab of salesperson's commission based a a 10% commission of each sale. Anyways, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}
I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong?
The Convert.ToDouble method will raise a FormatException if the string (returned from Console.ReadLine()) is not a valid number.
Typically, if you want to parse user input, it's a better idea to use Double.TryParse instead, as this lets you determine whether the input was a valid number without catching the exception.
This would normally look something like:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately
While Reed's answers is great, it's not the problem here.
What really happens is the same situation as this one
Console.Read only read the "Second part of the carriage return" and returns "". This is why the Convert fails.
replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine());
Replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());

Categories

Resources