You have multiple problems here.
Firstly, your "Error: Local variable 'userSalary' might not be initialized before accessing" problem:
While fields (class-level variables) are initialized to their default values when constructing a class, method variables are not initialized. To do so, you would need to assign a value to them. For example:
double userSalary = 0;
double leftOver = 0;
The next problem you have is that all variables are passed by value (i.e. a copy is made) and not by reference. Note that this is not to say that the types being passed are not reference types, but that the pointer the variable represents is passed as a copy. You can read more on that here.
What this means for you is that, while AskQuestion
changes its own userSalary
argument variable, it doesn't change the calling method's variable. One way to solve this is to use the ref
or out
keywords. (ref
is used where the variable is already initialized but the method changes it, out
is used where the method initializes the variable). More on that here.
So you could write your code like this:
static void AskQuestion(out double userSalary)
And then call it like so:
double userSalary;
AskQuestion(out userSalary);
or simply:
AskQuestion(out double userSalary);
Though a better approach is to have the method simply return the result. We'll also remove the leftOver
argument from CalculateTax
as that isn't used anywhere:
Note : You should always use TryParse
Style methods to validate user input
static double AskQuestion()
{
double userSalary;
Console.WriteLine("What is annual your salary?");
// simple validation loop
while (!double.TryParse(Console.ReadLine(), out userSalary))
Console.WriteLine("You had one job... What is annual your salary?");
return userSalary;
}
static void CalculateTax(double userSalary)
{
if (userSalary <= 14_000) //10%
{
Console.WriteLine("You are in Tax Category 1. 10% of your Salary goes to the state!");
Console.WriteLine("Calculating Salary...");
Thread.Sleep(500);
double leftOver = userSalary - (userSalary * 10 / 100);
Console.WriteLine("Your Salary after taxation is: $" + leftOver);
}
}
And then initialize userSalary
and call CalculateTax
like so:
userSalary = AskQuestion();
CalculateTax(userSalary);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…