The problem
Th e Chat-A-While phone company provides service to six
area codes and charges the per-minute rates for phone calls
shown in the accompanying table.
Area Code Per-Minute Rate ($)
262 0.07
414 0.10
608 0.05
715 0.16
815 0.24
920 0.14
Write a program that allows a user to enter an area code and
the length of time for a call in minutes, then display the total
cost of the call.
totalCharge use of unassigned local variable . please help
What I have done so far
int[] areaCode = new int[] { 262, 414, 608, 715, 815, 920 };
double[] perMinuteRate = new double[] { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };
string inputString, inputString1;
int validAreaCode;
double totalCharge, inputLength;
double areaCodexPerMinuteRate = 0;
Console.WriteLine("Pleas enter zipcode ");
inputString = Console.ReadLine();
validAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("Please enter the length of the call");
inputString1 = Console.ReadLine();
inputLength = Convert.ToDouble(inputString1);
bool found = false;
for (int x = 0; x < areaCode.Length; ++x)
{
if( validAreaCode == areaCode[x])
{
found = true;
areaCodexPerMinuteRate = perMinuteRate[x];
totalCharge = areaCodexPerMinuteRate * inputLength;
}
}
if (found)
{
Console.WriteLine(" The call was {0} long and it will cost you {1}", inputLength, totalCharge);
}
else
Console.WriteLine(" We do not support such zipcode");
Loading
VulpesPosted Jan 7, 2012, 1:45 PM
As the 'definite assignment' rules - as they are called - are complex, it's usually best to give local variables a harmless default value unless they're definitely going to be assigned a value in the next few lines.
In this case, I'd change this line:
double totalCharge, inputLength;
to:
double totalCharge = 0, inputLength;
and it should then compile (and work) OK.
Prime bPosted Jan 7, 2012, 2:50 PM
VulpesPosted Jan 7, 2012, 2:36 PM
Although it's not something which is often discussed, C#'s definite assignment rules can be tiresome at times.
Other languages (notably VB.NET) always give local variables a default value if you don't give them one yourself and so don't need such rules.
The trouble with this approach is that sometimes the developer can forget that the local variable has been given a default value which can lead to errors. The C# language designers, rightly or wrongly, decided it would be better not to give local variables default values but leave the compiler to detect whether the local variable had definitely been given a value before it was used.
The underlying philosophy is that it's better to detect potential errors at compile time rather than leave them to emerge at runtime.
However, the 'definite assignment' approach still has the problem that, whilst it may be clear to the developer that the variable has been given a value, it may not be clear to the compiler which (of necessity) must follow some rigid rules to determine this.
Prime bPosted Jan 7, 2012, 2:21 PM
Prime bPosted Jan 7, 2012, 2:12 PM