c# console application unassigned local variable [duplicate] - c#

This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 7 years ago.
int ValueOne, ValueTwo, Numchar, Total;
Console.WriteLine("This Is A Program For doing any Of the four mathematical Proccesses");
Console.WriteLine("You can Add , substract , Divide And Multiply");
Console.WriteLine("When Asked Please Type The Values Or The Proccesses You Want.");
Console.WriteLine("Please Type The First Value");
ValueOne = Convert.ToInt32((Console.ReadLine()));
Console.WriteLine("Please Type The Second Value");
ValueTwo = Convert.ToInt32((Console.ReadLine()));
Console.WriteLine("Please Enter The Number Of The Proccess/Character You Want Meaning That (1 = +) , (2 = -) , (3 = *) , (4 = /)");
Numchar = Convert.ToInt32((Console.ReadLine()));
if (Numchar == 1)
Total = ValueOne + ValueTwo;
if (Numchar == 2)
Total = ValueOne + ValueTwo;
if (Numchar == 3)
Total = ValueOne * ValueTwo;
if (Numchar == 4)
Total = ValueOne / ValueTwo;
Console.WriteLine("The Total Is :");
Console.WriteLine(Total);
Console.ReadLine();
the Console.WriteLine(Total);
at the end is apparently an unassigned local variable , though it should be assigned from the Lines beneath the "If" lines, also note that I'm new in visual studio and i just started taking The Courses , also , i don't think this is a duplicate because the other post's fix Didn't Work for me.

Let's say that your code didn't produce an error, and compiled and ran. What do you think would happen if NumChar wasn't 1, 2, 3, or 4?
Your code would never reach any of the statements in your ifs there, and would never assign an initial value to Total. Since this is entirely possible given your program (and would be impossible to check for in general -- see the Halting Problem), the error is substantiated and necessary.

Related

I don't understand how 'i' become 4 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
how does the optput come as
3
3
4
I don't understand how 'i' become 4 for last
code:
int i = 2;
Console.WriteLine(++i);
Console.WriteLine(i++);
Console.WriteLine(i);
Because you first used the prefix increment operator and then used postfix.
int i = 2;
Console.WriteLine(++i); // i became 3 *before it was used*
Console.WriteLine(i++); // i first used, still 3, and then incremented becoming 4
Console.WriteLine(i); // i is still 4
In c# assigning a value to a variable also returns a value. Usually it is the value that is assigned
Here is an assignment, the current time is assigned to the now variable:
DateTime now = DateTime.Now;
This assignment also results in a returned value of the current time. It means you can legally write this:
DateTime now;
Console.WriteLine(now = DateTime.Now);
Not only will your now variable end up set to the current time, but the value of what was assigned is printed out, so the current time is printed
This is also an assignment:
int i = 2;
And so is this:
++i;
It is short for this:
i = i + 1;
Now because we know assignments return values we know it's legal to print out assignments:
Console.WriteLine(i = i + 1);
If i was 2, the sum on the right would be evaluated to give 3, then 3 would be assigned into i, and then also 3 is returned so 3 prints out in the console
i++ is more like a special case, where the value that i was BEFORE the assignment is made, is printed out. You can think of i++ as working like:
int i_before = i; //remember it
i = i + 1;
return i_before; //return the old value
So this:
Console.WriteLine(i++);
If i is 3 already, it will be incremented to 4, but 3 is returned and printed
The easy way to remember the difference between i++ and ++i is:
"in i++ the i is before the ++ so the value you get returned is what i was before it was incremented"
If you just use the increment as a statement on its own, it makes no difference which you use:
int i = 2;
i++;
++i;
Console.WriteLine(i); //4
It only matters which you use if you are relying on the "assignment returns a value" behavior
By the time the last line of your code comes around, i is 4 because it has been incremented twice, from 2
i starts out as 2.
On the first line, you (pre) increment it to 3, and then print it out.
On the second line, you print it out and then increment it (post increment), so it's now 4.
On the last line, you just print out the current value, which is 4, as noted above.

C# increment a variable and convert to string on one line [duplicate]

This question already has answers here:
Pre- & Post Increment in C#
(6 answers)
Closed 5 years ago.
Simple request -- does anybody know a way to consolidate this to one line:
edit - I was NOT confused about pre vs post increment operators. The question I posted should have worked, I honestly do not know what happened. somewhere between VS and SO I fixed it.
startingMask++;
string mask2 = startingMask.ToString().PadLeft(3, '0');
Something like
string mask2 = (startingMask++).ToString().PadLeft(3, '0');
edit -- Alright -- chill out -- :)
Here is the final full solution, I should have provided more info in my first question, I was just looking for a nudge in the right direction (the number needed and starting number will be changing via a database pull at some point):
int startingMask = 76;
int numberNumberNeeded = 10;
List<string> masks = new List<string>();
while (numberNumberNeeded > 0)
{
string newMask = (startingMask++).ToString().PadLeft(3, '0');
masks.Add(newMask);
numberNumberNeeded--;
}
string mask2 = (++startingMask).ToString().PadLeft(3, '0');
Postfix ++ startingMask++ first take value and then increment value
Sufix ++ ++startingMask first increment value and then take value

How do you use a value generated inside a nested if else in a for loop? [duplicate]

This question already has answers here:
Why did I get the compile error "Use of unassigned local variable"?
(10 answers)
Closed 5 years ago.
double usd, usd2;
for (int x = 0; x < 14; x++)
{
if (usd >= principle[x * 2] && usd <= principle[x * 2 + 1])
{
usd2 = usd + fee[x];
break;
}
}
peso = usd2 * 50.26;
principle[] is an array of price ranges principle[0] - principle[1]. usd2 is supposed to be the usd with an added fee. I wanted to use the usd2 after but it errors at the `peso = usd2 * 50.26 and it says "use of unassigned local variable usd2".
Should I use return? I am using an array to check the price usd in the principle(price ranges). I am using c#
The compiler can't guarantee that a value is ever assigned. You need to provide a default value:
double usd = 0.0D;
double usd2 = 0.0D;
The way the compiler can at least guarantee that if the loop or the if are never entered then something is still assigned to that variable.

Float calculation showing difference. Positive showing negative? [duplicate]

This question already has answers here:
Always return positive value
(9 answers)
Closed 5 years ago.
I am calculating the difference between two numbers. If the calculation ends up being 5 - 10, it equals to "-5". If this is the case I need results to display/equal to "+5" , with the "+" sign.
I basically need reverse. So same if 10 - 5 quals to "5" I need it to display as "+5"
Code below I am using:
float rowresults = ROW1 - ROW2;
Textbox.text = rowresults.ToString();
Math.Abs is what you are looking for:
float rowresults = Math.Abs(ROW1 - ROW2);
And to add the "+"-sign to the front of the text (without changing your elsewise existing behaviour):
Textbox.text = "+" + rowresults.ToString();

Cannot convert type 'String' To 'Int'?

okay so, I have been asked to write a console application for a theater ticket system. A user will type in the number of seats required, and the area of the theater chosen (using the code number 1-4 to represent the seating area chosen) The program should work out and display the cost of the tickets, based on the pricing plan shown below
Area Code price
Stalls 1 £24
Grand circle 2 £30
Upper circle 3 £27
Gallery 4 £20
I've so far came up with the following, But it's got an error to do with string + Int conversions under the IF Statements section, this is probably very easy to fix, but I'm new to programming so i'm unsure how to resolve it:
//Declare variables and constants
int iSeatNum;
int iArea;
int iCost;
int iTotalCost;
//Ask the user how many seats they require
Console.WriteLine("How many seats would you like to purchase?");
iSeatNum = Convert.ToInt32(Console.ReadLine());
//Ask the user what area they would like to be in
Console.WriteLine("Where would you like to sit? Please enter 1 for Stalls, 2 for Grand Circle, 3 for Upper Circle or 4 for Gallery");
iArea = Convert.ToInt32(Console.ReadLine());
**if (iArea = "1")**
{
iCost = 24;
}
//Clarify information & work out
Console.WriteLine("You are buying " + iSeatNum + " Seats at " + iArea);
iTotalCost = iSeatNum * iCost;
Console.WriteLine("Your total ticket cost is " + iTotalCost);
//Prevent from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
if (iArea = "1")
iArea is an integer, "1" is a string. So you cannot compare those two. You should compare with the integer 1 instead. Also note that a single equals symbol (=) is an asignment, and not a comparison. You will want to use two there: ==
if (iArea == 1)
now it displays a further error, when I put iTotalCost = iSeatNum * iCost; it comes up the error of "Use of unassigned local variable iCost" Any idea how I fix this?
The problem is that you declare the variable iCost at the beginning, but never safely assign any value to it before using it. You do assign a value when iArea equals to 1, but for all other cases, the variable remains uninitialized. Of course the compiler doesn’t know that you will end up typing in 1 when the program runs for testing, and that’s not a safe thing anyway. So it requires you to initialize your variable with anything instead.
So at the beginning, you can just say int iCost = 0; to fix this.
Well "1" is a string, not int.
if (iArea == 1)
Because you have already converted you string (the Console.ReadLine() return a string) into number using:
iArea = Convert.ToInt32(Console.ReadLine());
you can compare it as number using:
if (iArea == 1)
note the == instead of =, the single is used for assignment, the double for comparison.
if (iArea = "1")
This doesn't make sense. First of all you're using the assignment equals operator. You're attempting to assign iArea the value of "1". Instead, you need the logical equality operator == which will return true or false depending on whether the first operand is equal to the second operand.
Second, you have already converted the string value read from the console to a strongly typed integer. So you need to write your if statement as follows:
if (iArea == 1)
String strArea =Console.ReadLine();
if (strArea.Equals("1"))
{
iCost = 24;
}
or
int iArea = Convert.ToInt32(Console.ReadLine());
if (iArea == 1))
{
iCost = 24;
}

Categories