Method not launching [duplicate] - c#

This question already has answers here:
how to call non static method in window console application
(5 answers)
Closed 4 years ago.
I just started c#, thank you all for your patience. I am following a course on udemy and i dont understand why my method is not launching.
Here is my code:
public class Program
{
public void Exercise1()
{
Console.Write("Enter a number between 1 to 10: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
if (number >= 1 && number <= 10)
Console.WriteLine("Valid");
else
Console.WriteLine("Invalid");
}
static void Main(string[] args)
{
Exercise1(); // my method is not appearing in intelisense, what am i doing wrong?
}
}

Just mark the method as static:
public class Program
{
public static void Exercise1()
{
Console.Write("Enter a number between 1 to 10: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
if (number >= 1 && number <= 10)
Console.WriteLine("Valid");
else
Console.WriteLine("Invalid");
}
static void Main(string[] args)
{
Exercise1();
}
}
The problem is that Main is static, meaning it doesn't need an instance of Program to run. If you want Main to call other methods in Program, those methods also need to be static.
The only other way to do it would be this:
public class Program
{
public void Exercise1()
{
Console.Write("Enter a number between 1 to 10: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
if (number >= 1 && number <= 10)
Console.WriteLine("Valid");
else
Console.WriteLine("Invalid");
}
static void Main(string[] args)
{
var prog = new Program();
prog.Exercise1();
}
}

Related

This code, no error at building, but error at showing console

using System;
namespace A
{
class program
{
public static int FibonacciRecursive(uint number)
{
if (number == 0) return 0;
if (number == 1) return 1;
return FibonacciRecursive(number - 2) + FibonacciRecursive(number - 1);
}
static void Main(string[] args)
{
FibonacciRecursive(10);
}
}
}
I have no idea to solve this obstacle.
Output-window said it suceeded to build.

Do functions execute loops when called?

I'm trying to write a program that consists of some items (only 2 of them for now). It doesn't show any errors in the console, but when I try to call the Main function more than once, it doesn't execute the loops inside. Here's the code by the way.
public static class Program
{
public static string input = Convert.ToString(Console.ReadLine());
public static int health = 100;
public static int energy = 100;
public static void Main()
{
Console.WriteLine("This is a game used for testing items");
Console.WriteLine("Would you like to use items or get them? (Typing in status shows the value of your health and energy)");
if (Program.input == "get")
{
Items.GetItems();
}
if (Program.input == "use")
{
ItemUser();
}
if (Program.input == "status")
{
StatusChecker();
}
}
public static void StatusChecker()
{
Console.WriteLine("Your health is " + Program.health);
Console.WriteLine("Your energy is " + Program.energy);
}
public static void ItemUser()
{
Console.WriteLine("What do you want to use?");
string useChecker = Convert.ToString(Console.ReadLine());
if (useChecker == "healthPotion")
{
health += 100;
Items.healthPotion--;
}
if (useChecker == "energyDrink")
{
energy += 100;
Items.energyDrink--;
}
}
}
public static class Items
{
public static int healthPotion = 0;
public static int energyDrink = 0;
public static void GetItems()
{
Console.WriteLine();
string itemChecker = Convert.ToString(Console.ReadLine());
if ( itemChecker == "health potion")
{
healthPotion++;
Program.Main();
}
if (itemChecker == "energy drink")
{
energyDrink++;
Program.Main();
}
}
So I wanted the program to get the values after updating them, but it just stops after I call Main method more than once. Can anyone help me?
(I'm not that great at coding so I couldn't make really efficient code)
You don't have any loops inside your Main method and every time you run the application you start from scratch and each of your variables contain initial values. If I get right what you're trying to achieve, I would suggest you to write the Main method like this to have loop which will ask a user for a command until the user enters "quit":
static void Main(string[] args)
{
Console.WriteLine("This is a game used for testing items");
while (true)
{
Console.WriteLine("Would you like to use items or get them? (Typing in status shows the value of your health and energy)");
string userAnswer = Console.ReadLine();
if (userAnswer == "quit") break;
if (userAnswer == "get")
{
Items.GetItems();
}
if (userAnswer == "use")
{
ItemUser();
}
if (userAnswer == "status")
{
StatusChecker();
}
}
}
I noticed also that when you call ItemUser method you update static variables of your Items class, but in the StatusChecker method you write to the console variables of your Program class. They are actually different, so I think in your StatusChecker method you may want do the following:
public static void StatusChecker()
{
Console.WriteLine("Your health is " + Items.health);
Console.WriteLine("Your energy is " + Items.energy);
}
You are assigning a variable here:
public static string input = Convert.ToString(Console.ReadLine());
So the next time you call your "Main" method it will use the value you typed in the first time your app executed. If you want it to ask each time you'll need to do something like this:
public static void Main()
{
input = Convert.ToString(Console.ReadLine());
...
}
Another thing is that it can exit after the first call if you type in i.e. "status".
Issue number 3 is that this is not the "nice" way to write a program. The Main method is supposed to be executed when your app starts as it is the entry point (more on that here).

New to C# and OOP can someone explain this scope issue to me?

I haven't done much work with lists and OOP programming before so I am sorry if this is a simple formatting or visibility issue.
This is a method which is currently defined at the very top of my code
namespace CrazyMaths
{
class Program
{
static int getMemory()
{
Console.WriteLine("Please enter a number");
int locationChoice = int.Parse(Console.ReadLine());
int result = storeValues[locationChoice];
return result;
}
This is part of a separate method which calls getMemory()
else if (tempNumber == "M")
{
result = getMemory();
test = true;
}
And this is the main block of code in which I declare my list.
static void Main(string[] args)
{
List<int> storeValues = new List<int>();
The name 'storeValues' does not exist in the current context.
You should call your method like below passing the storeValues list to the function getMemory(). Else it's obviously not accessible since storeValues is defined within main() method and so it's scope is bounded within the main() method only.
getMemory(storeValues)
So your main() should look like
static void Main(string[] args)
{
List<int> storeValues = new List<int>();
getMemory(storeValues);
You should declare storeValues outside the Main function like this:
namespace CrazyMaths
{
class Program
{
private List<int> storeValues;
static int getMemory()
{
Console.WriteLine("Please enter a number");
int locationChoice = int.Parse(Console.ReadLine());
int result = storeValues[locationChoice];
return result;
}
static void Main(string[] args)
{
storeValues = new List<int>();
}

Display sum and average of numbers 1 to 100 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a simple program in C# to display the sum and the average of the numbers 1 to 100. the output should look like...
the sum is 5050
the average is 50.5
I cant seem to get it to work properly though, the return value only returns the sum not the wording before it, I have tried other ways for it to display the message and sum and ave but they arent working. I am trying to do this using the model view view controller method, but cant understand where I am going wrong and how to get it to display the above result. my code is below.
class SumAndAverage
{
public float sum = 0;
public float ave = 0;
public float SumAndAve()
{
for (int i = 1; i <= 100; i++)
{
sum = sum + i;
ave = sum / i;
}
return sum + ave;
}
}
}
class SumAndAverageController
{
IView view;
SumAndAverage sumAndAverage;
public SumAndAverageController(IView theView, SumAndAverage theSumAndAverage){
view = theView;
sumAndAverage = theSumAndAverage;
}
public void Go()
{
view.Start();
//mAndAverage.SetNumber(view.GetString("Please enter a number"));
view.Show(sumAndAverage.SumAndAve());
//view.Show(sumAndAverage.Result());
view.Stop();
}
}
class ConsoleView : IView
{
public void Start()
{
Console.Clear();
}
public void Stop()
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
public void Show<T>(T message)
{
Console.WriteLine(message);
}
}
interface IView
{
void Start();
void Stop();
void Show<T>(T message);
}
class Program
{
static void Main(string[] args)
{
new SumAndAverageController(new ConsoleView(), new SumAndAverage()).Go();
}
}
using System;
using System.Linq;
namespace SumAndAverage
{
class Program
{
static void Main(string[] args)
{
var data = Enumerable.Range(1, 100);
Console.WriteLine("the sum is " + data.Sum());
Console.WriteLine("the average is " + data.Average());
}
}
}

Variable scope problems C#

I'm learning C# and i'm having problems with variable scope in my simple console program.
The program runs perfectly so far except I know I will encounter issues when trying to reference variables previously instantiated.
I have tried to change methods from static to non static and also applied public/private access but to no avail.
I just need a nudge in the right direction, hope someone can help!
The error message i'm getting is :
Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication2.Program.game()'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
int numberToGuess;
int numberGuessed;
int triesRemaining;
public void game()
{
Console.WriteLine(" ==Welcome to Guess My Number== \n");
Console.WriteLine("Player 1: Please enter your number to guess between 1 and 20: \n");
numberToGuess = int.Parse(Console.ReadLine());
Console.WriteLine("Player 2, please enter your first guess, you have 7 tries: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
correct();
}
else
{
incorrect();
}
}
public void correct()
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
}
public void incorrect()
{
}
static void Main(string[] args)
{
game();
}
}
}
instance members (those not marked with the static keyword) exist once per object instance. Every instance of an object gets its own copies of them.
static members, on the other hand, exist once for the entire class and are shared by all object instances.
So, If you've got a class:
class Foo
{
public static int Alpha { get ; set ; }
public int Bravo { get ; set ; }
}
No matter how many instances of your Foo class are created, there is only one instance of Alpha. Any instance method or property can access a static member directly.
Instance members, since they exist on a per-instance basic, require an object instance to reference them. If you add some methods to the Foo class:
public static int DoSomething()
{
return Alpha * 3 ;
}
is perfectly valid — the method is static and the member is static. Ditto for an instance method:
public int DoSomethingElse()
{
return Alpha * 3 ;
}
Something like this will fail:
public static int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + Bravo ;
}
Bravo can't be referenced here without a reference to an instance of Foo. This will work however:
public static int AndNowForSomethingCompletelyDifferent( Foo instance )
{
return Alpha * 3 + instance.Bravo ;
}
As will this:
public int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + Bravo ;
}
Since the method is non-static (an instance method), it has an implicit reference (this) to its instance of Foo. The above is exactly equivalent to
public int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + this.Bravo ;
}
In your case, you could instantiate the class Program in your Main() method:
public static void Main( string[] args )
{
Program p = new Program() ;
p.game() ;
return ;
}
Or you could mark your methods game(), correct() and incorrect() as static, just as the Main() method is marked.
Hope this helps!
static methods/fields belong to the user-defined type, not the instance.
For example, if you look at this piece of code:
public class MyClass
{
public static void Foo()
{
}
}
the Foo() method, is not accessed from an instance of MyClass. Since it is static, you access it from the user-defined type itself. Ex:
public class Program
{
static void Main(String[] args)
{
MyClass.Foo();
}
}
Since Main() is static, you can only reference static methods or variables inside it (this excludes methods referenced from local instance variables).
In your code, the method game() and the fields/methods being called/invoked by game are not static, therefore you would only be able to access it via an object instance. Of course, making game() and all the other fields/methods static would result in a working piece of code.
For more information on static types, look here: http://msdn.microsoft.com/en-us/library/98f28cdx.aspx
I have gone on to complete the methods and it seems to be working great!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
int numberToGuess;
int numberGuessed;
int triesRemaining = 7;
string playAgain;
string player1, player2;
public void game() //Initiates the game instance
{
Console.WriteLine(" ==Welcome to Guess My Number== \n");
Console.WriteLine(" Player 1, Please enter your name: \n");
player1 = Console.ReadLine();
Console.Clear();
Console.WriteLine(" ==Guess My Number== \n");
Console.WriteLine("Hello " + player1 + " : Please enter your number to guess between 1 and 20: \n");
numberToGuess = int.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(" ==Guess My Number== \n");
Console.WriteLine(" Player 2, Please enter your name: \n");
player2 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Hello " + player2 + " please enter your first guess, you have 7 tries: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
newGame();
}
else
{
incorrect();
}
}
public void incorrect() //Method for dealing with incorrect answers
{
for (int x = 0; x < 6; x++)
{
triesRemaining--;
Console.WriteLine("Incorrect, you have " + triesRemaining + " tries remaining \n");
Console.WriteLine(player2 + ", please enter your next guess: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
newGame();
}
else {
//Do nothing
}
}
Console.WriteLine("You have used up all your tries! You have failed. The number was: " +numberToGuess + "\n");
newGame();
} //Method for dealing with incorrect answers
public void newGame() //Method that gives the user the option to start a new game instance
{
Console.WriteLine("Would you like to play again? Type yes or no: \n");
playAgain = Console.ReadLine();
playAgain = playAgain.ToLower();
if (playAgain == "yes")
{
Console.Clear();
game();
}
else if (playAgain == "y")
{
game();
}
else
{
//Do nothing
}
}
static void Main(string[] args)
{
new Program().game();
}
}
}

Categories