how to call " static void Main(string[] args) "in the class again - c#

i am new in C# and working on Console Applications now a days i wrote the following code :
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch06Ex01
{
class Program
{
static void Write()
{
Console.WriteLine("Please enter any string..!!");
}
static void Main(string[] args)
{
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
string selectedOption = Console.ReadLine();
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
//else if (selectedOption == "n")
{
//Terminate the Program
}
Console.ReadKey();
}
}
}
Now at the point :
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
i wanted to reboot the program if User enter "y" and terminate it if the user enter "n", for this purpose firs of all i tried to use goto statement like :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch06Ex01
{
class Program
{
static void Write()
{
Console.WriteLine("Please enter any string..!!");
}
static void Main(string[] args)
{
StartPoint;
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
string selectedOption = Console.ReadLine();
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
goto StartPoint;
}
//else if (selectedOption == "n")
Console.ReadKey();
}
}
}
but it didn't work for me at StartPoint; it gives error that
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement C:\Users\Ahsan\Desktop\C# for Beginners Examples\Ch06Ex01\Ch06Ex01\Program.cs 18 13 Ch06Ex01
then i tried to call main function itself at point
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
but it gives me a lot of error here , don' know how to do it now, can any one help me out ? don't know how to do this thing work....
calling " static void Main(string[] args) "in the class again would be preferred....

Firstly, your label is incorrect. The end of a label should have a colon character :.. so your label should have been this:
StartPoint:
However:
You should just loop until a condition is met. In this case.. the condition is to not restart:
bool running = true;
while (running) {
/*
* all of your other code
* should go here
*/
if (selectedOption != "y") {
running = false;
}
}

You realy should not use a goto or call your Main again (recursion), do while is a better solution to repeat your logic muliple times:
string selectedOption;
do {
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
selectedOption = Console.ReadLine();
} while (selectedOption == "y")
Console.ReadKey();

Just call the method again, passing in the same arguments that where passed in initially, also try to avoid using goto if you can:
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
Main(args);
}

Try put the code that you will execute outside the main class in another method like
void execute()
{
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
string selectedOption = Console.ReadLine();
}
then in the main
static void Main(string[] args)
{
bool run = true
while(run){
execute()
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
selectedOption = Console.ReadLine();
if (selectedOption == "n")
{
run = false;
}
}
}

something like this :
static void Main(string[] args)
{
string selectedOption = "";
do
{
...........
}
while (selectedOption == "y")
if (selectedOption == "n")
{
//Terminate the Program
}
}

Related

C# Console.ReadLine creates new line with every keypress

I've encountered this weird issue that might be connected to my IDE or C# overrall.
Whenever I am inputting something in the console that is being read my Console.ReadLine(), it is being duplicated and shown below until I press return. I want to input a whole String for example, but what I see is reading char by char which kind of messes up debugging and presence of my program. I am attaching the code below along with the screenshot of the issue.
using System;
using System.Text.RegularExpressions;
namespace Zadanie_1
{
class Program
{
static void ShowMenu()
{
Console.WriteLine("Witaj w grze Siszarp!");
Console.WriteLine("[1] Zacznij nową grę");
Console.WriteLine("[X] Zamknij program");
}
static void PickOption(ConsoleKeyInfo keyPressed)
{
switch (keyPressed.KeyChar)
{
case '1':
Console.Clear();
Option1Picked();
break;
case 'X':
Environment.Exit(0);
break;
}
}
static bool IsCharacterNameValid(String characterName)
{
if (characterName.Length < 2)
{
Console.WriteLine("Niepoprawna nazwa!");
return false;
}
if (!Regex.IsMatch(characterName, #"^[a-zA-Z]+$"))
{
Console.WriteLine("Niepoprawna nazwa!");
return false;
}
return true;
}
static void EnterCharacterName()
{
String characterName;
do
{
Console.Write("Podaj nazwę bohatera:");
characterName = Console.ReadLine();
} while (!IsCharacterNameValid(characterName));
}
static void Option1Picked()
{
EnterCharacterName();
}
static void Main(string[] args)
{
ShowMenu();
ConsoleKeyInfo keyPressed = Console.ReadKey();
PickOption(keyPressed);
}
}
}

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).

Loop a method call based on user choice

Based on the user choice can we call the method infinitely. If a User presses the Key "Y", call the method, else quit the console app.
Below is the code:
namespace IR_CSharp
{
class Program
{
private void GetASCIIValue()
{
Console.WriteLine("Enter a value to get the ascii value: ");
int value = Console.Read();
Console.WriteLine("ASCII value is {0}", value);
Console.ReadKey();
}
static void Main(string[] args)
{
Program prog = new Program();
string choice = "0";
prog.GetASCIIValue();
}
}
}
class Program
{
static void Main(string[] args)
{
ConsoleKeyInfo keyinfo;
do
{
Console.WriteLine("Enter a value to get the ascii value: ");
int value = Console.Read();
Console.WriteLine("ASCII value is {0}", value);
keyinfo = Console.ReadKey();
}
while (keyinfo.Key != ConsoleKey.Y);
}
}

C# Can I use a int declared in the main() in a extern bool?

So, I was trying to make a program that given three numbers, the one that i one to see if it's between the other two and the other two, says if the first number is between the others.
I wanted to do so with a outside the main() program bool, but when i try to call the variables declarated in the main says "The name 'a' does not exist in the current context"
Is there any way to use a int declared in main in a extern boolean?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine("number to check");
int a; a = int.Parse(Console.ReadLine());
Console.WriteLine("1st range");
int rang1; rang1 = int.Parse(Console.ReadLine());
Console.WriteLine("2n range:");
int rang2; rang2 = int.Parse(Console.ReadLine());
if (EnRang() = true) { Console.WriteLine("Number {0} is between {1} and {2}", a, rang1, rang2); }
else if (EnRang() = false)
{ Console.WriteLine("The number {0} isn't between {1} and {2}", a, rang1, rang2); }
else { Console.WriteLine("Something goes wrong."); }
}
public static bool EnRang()
{
int NumerBool = a; int RangA = rang1; int RangB = rang2;
if (a > RangA || a < RangB){ return true; }
else{ return false; }
}
}
This should get you pointed in the right direction. You need to pass the variables as parameters to you EnRang method.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("number to check");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("1st range");
int rang1 = int.Parse(Console.ReadLine());
Console.WriteLine("2n range:");
int rang2 = int.Parse(Console.ReadLine());
if (EnRang(a, rang1, rang2) == true)
{
Console.WriteLine("Number {0} is between {1} and {2}", a, rang1, rang2);
}
else if (EnRang(a, rang1, rang2) == false)
{
Console.WriteLine("The number {0} isn't between {1} and {2}", a, rang1, rang2);
}
else
{
Console.WriteLine("Something goes wrong.");
}
}
public static bool EnRang(int NumerBool, int RangA, int RangB)
{
if (NumerBool > RangA && NumerBool < RangB)
{
return true;
}
else
{
return false;
}
}
}

Method not launching [duplicate]

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();
}
}

Categories