Loop a method call based on user choice - c#

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

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

model view view controller C#

I am writing a simple program in c# which asks the user to enter a number, then tells the user if the number is odd or even. my program works however wheni first enter the number nothing happens, i have to enter the number twice and then it tells me if the number is odd or even, im not very good at using the mvvc technique, so if anyone knows why this is happening and could help me that would be great.my code is below...
class CheckNumber
{
protected String number;
public void SetNumber(String newNumber)
{
number = newNumber;
}
public int Number()
{
int number = Convert.ToInt32(Console.ReadLine());
if (number % 2 == 1) //(number % 2 == 0) would test for even numbers(0 remainder)
{
Console.WriteLine("Odd number");
}
else
{
Console.WriteLine("Even number");
}
return number;
}
}
class CheckNumberController
{
IView view;
CheckNumber checkNumber;
public CheckNumberController(IView theView, CheckNumber theCheckMark)
{
view = theView;
checkNumber = theCheckMark;
}
public void Go()
{
view.Start();
checkNumber.SetNumber(view.GetString("Please enter a number"));
view.Show(checkNumber.Number());
view.Stop();
}
}
class ConsoleView : IView
{
public void Start()
{
Console.Clear();
}
public void Stop()
{
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
public String GetString(String prompt = "")
{
Console.WriteLine(prompt);
return Console.ReadLine();
}
public Int32 GetInt(String prompt = "")
{
Console.WriteLine(prompt);
return Int32.Parse(Console.ReadLine());
}
public void Show<T>(T message)
{
Console.WriteLine(message);
}
}
interface IView
{
void Start();
void Stop();
String GetString(String prompt);
Int32 GetInt(String prompt);
void Show<T>(T message);
}
class Program
{
static void Main(string[] args)
{
new CheckNumberController(new ConsoleView(), new CheckNumber()).Go();
}
}
You're reading input twice. Firstly in the CheckNumberController.Go()
checkNumber.SetNumber(view.GetString("Please enter a number"));
And secondly in CheckNumber.Number()
int number = Convert.ToInt32(Console.ReadLine());
The latter should be:
int number = Convert.ToInt32(this.number);
As you want to work on the value you've already read and set, not an additional one
public String GetString(String prompt = "")
{
Console.WriteLine(prompt);
//return Console.ReadLine();
return "error is here";
}
When calling GetString() method your again trying to get an input. Just comment and return string if you want.
The key is in this method:
public void Go()
{
view.Start();
checkNumber.SetNumber(view.GetString("Please enter a number"));
view.Show(checkNumber.Number());
view.Stop();
}
SetNumber(string) sets the protected field number in the CheckNumber class. However, when you call view.Show<T>(T), you are calling the Number() method on the CheckNumber class, which ignores the stored variable and reads from the console again.

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

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
}
}

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