Passing Variable through function to main()
I'm very new to C# but am learning more and more every day. Today, I'm trying to build a simple console calculator and need help passing a variable from the function to Main() so I can use it in an if-else to determine what function should execute.
public static void Main(string[] args)
{
int decision = Introduction();
Console.Clear();
Console.WriteLine(decision);
Console.ReadLine();
}
public static int Introduction()
{
int decision = 0;
while (decision < 1 || decision > 7)
{
Console.Clear();
Console.WriteLine("Advanced Math Calculations 1.0");
Console.WriteLine("==========================");
Console.WriteLine("What function woul开发者_Go百科d you like to perform?");
Console.WriteLine("Press 1 for Addition ++++");
Console.WriteLine("Press 2 for Subtraction -----");
Console.WriteLine("Press 3 for Multiplication ****");
Console.WriteLine("Press 4 for Division ////");
Console.WriteLine("Press 5 for calculating the Perimeter of a rectangle (x/y)");
Console.WriteLine("Press 6 for calculating the Volume of an object (x/y/z)");
Console.WriteLine("Press 7 for calculating the standard deviation of a set of 10 numbers");
decision = int.Parse(Console.ReadLine());
if (decision < 1 || decision > 7)
{
decision = 0;
Console.WriteLine("Please select a function from the list. Press Enter to reselect.");
Console.ReadLine();
}
else
{
break;
}
}
return decision;
}
When I try to use decision up in Main() it says "The name decision does not exist in the current context".
I'm stumped and tried googling it to no avail.
Cheers
SUCCESS!
Return the value from Introduction
. The value is local to the method and to use it elsewhere you need to return it and assign to a local variable. Alternatively, you could make decision
a static class variable, but that's not a particularly good practice, at least in this case. The Introduction
method (not a particularly good name, IMO, it should probably be GetCalculationType()
since that is what it is doing) typically shouldn't have any side-effects.
public static void Main( string[] args )
{
int decision = Introduction();
...
}
public static int Introduction()
{
int decision = 0;
...
return decision;
}
Main()
is the entry point for your app. It then calls your method Introduction()
which adds a new stack frame on the stack. Because you declare the decision variable inside your Introduction method, the Main method has no knowledge of it.
If you instead declare your decision variable outside both methods, you should be able to reference it from either:
int decision;
static void Main(string[] args)
{
// code here
}
static void Introduction()
{
// code here
}
You can't use the decision
variable in main since it is local to the function Introduction
.
You could make decision
a static class variable but better would be to return the value from Introduction
and assign it to a local variable in main.
精彩评论