Reputation: 861
So I am supposed to make a method with a return value:
private decimal ReadInputThree()
{
Console.WriteLine("Ange valuta kursen:");
decimal CurrencyValue = decimal.Parse(Console.ReadLine());
return CurrencyValue;
}
And then using another method to use the CurrencyValue:
if (done == true)
{
ReadInputTwo();
ReadInputThree();
Sum = Sum / CurrencyValue;
Console.WriteLine("Värdet av valutan {0} är {1}", CurrencyName, CurrencyValue);
}
But when I run it, it tells me it can divide Sum with CurrencyValue, as CurrencyValue is set to 0. But how can that be? It should be whatever the user tells it to? I even wrote a WriteLine statement after ReadInputThree in the if statement to se if it would print the input string and it did.
Upvotes: 0
Views: 166
Reputation: 158
Get return value from method. Also check for valid input and divide by zero exception.
private decimal ReadInputThree()
{
Console.WriteLine("Ange valuta kursen:");
string userValue = Console.ReadLine();
decimal CurrencyValue = 0;
decimal.TryParse(userValue, out CurrencyValue);
return CurrencyValue;
}
if (done == true)
{
ReadInputTwo();
decimal CurrencyValue = ReadInputThree();
if (CurrencyValue != 0)
{
Sum = Sum / CurrencyValue;
}
else
{
Sum = 0;
}
Console.WriteLine("Värdet av valutan {0} är {1}", CurrencyName, CurrencyValue);
}
Upvotes: 0
Reputation: 26199
Problem : You are not holding the return value of the ReadInputThree()
function.so value of CurrenceyValue
variable stillbe Zero even after calling the ReadInputThree()
function.
Solution: You need to store the return value of the ReadInputThree()
function into CurrencyValue
variable
Try This:
CurrencyValue = ReadInputThree();
Sum = Sum / CurrencyValue;
Upvotes: 4
Reputation: 15941
Because you are not assigning the result of ReadInputThree
to CurrencyValue
:
if (done == true)
{
ReadInputTwo();
CurrencyValue = ReadInputThree();
Sum = Sum / CurrencyValue;
Console.WriteLine("Värdet av valutan {0} är {1}", CurrencyName, CurrencyValue);
}
Upvotes: 1