How to get a menu to loop - c#

I am looking to get the menu to loop so when I enter the help menu and then return to the main menu it will actually run. Instead it doesn't respond when anything is entered. The exit also does not work for whatever reason and therefore I would appreciate any help given. Thank you.
using System;
namespace MasterMind
{
class Menu
{
public void DrawMainMenu()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
}
public void DrawHelp()
{
Console.Clear();
Console.WriteLine("Rules Of MasterMind!");
Console.WriteLine("Mastermind is a game about guessing a 4 digit code. The numbers can range from");
Console.WriteLine("1-4 and any other numbers will be rejected. It will say in the CMD");
Console.WriteLine("prompt whether or not you had any of the number correct or false.");
Console.WriteLine("Press any key to go back to the main menu.");
Console.ReadKey();
Console.Clear();
DrawMainMenu();
Console.ReadLine();
}
public void DrawExit()
{
Console.Clear();
Console.WriteLine("You are about to exit the game");
Console.WriteLine("Are you sure: Y/N");
string userExit = Console.ReadKey().KeyChar.ToString();
if (userExit == "Y")
{
Environment.Exit(0);
}
if (userExit == "N")
{
DrawMainMenu();
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
var menu = new Menu();
menu.DrawMainMenu();
string userInput = Console.ReadKey().KeyChar.ToString();
if (userInput == "1")
{
}
if (userInput == "2")
{
Console.Clear();
menu.DrawHelp();
}
if (userInput == "0")
{
menu.DrawExit();
Console.ReadLine();
}
}
}
}

Something like this can get you started.
Note: there are improvements you can make to the structure and logic in various ways....I'll just give you one example e.g. having the Environment.Exit(0); where it is could be frowned upon...it could be avoided by having a "flag" on the while loop, which is set if you choose "exit", and then the program just exits naturally.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
using System;
namespace MasterMind
{
class Menu
{
public void DrawMainMenu()
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
}
public void DrawHelp()
{
Console.Clear();
Console.WriteLine("Rules Of MasterMind!");
Console.WriteLine("Mastermind is a game about guessing a 4 digit code. The numbers can range from");
Console.WriteLine("1-4 and any other numbers will be rejected. It will say in the CMD");
Console.WriteLine("prompt whether or not you had any of the number correct or false.");
Console.WriteLine("Press any key to go back to the main menu.");
Console.ReadKey();
}
public void DrawExit()
{
Console.Clear();
Console.WriteLine("You are about to exit the game");
Console.WriteLine("Are you sure: Y/N");
string userExit = Console.ReadKey().KeyChar.ToString();
if (userExit.ToUpper() == "Y")
{
Environment.Exit(0);
}
}
}
class Program
{
static void Main(string[] args)
{
var menu = new Menu();
while (true)
{
menu.DrawMainMenu();
string userInput = Console.ReadKey().KeyChar.ToString();
if (userInput == "1")
{
Console.Clear();
Console.WriteLine("Playing...");
Console.ReadKey();
}
if (userInput == "2")
{
menu.DrawHelp();
}
if (userInput == "0")
{
menu.DrawExit();
}
}
}
}
}
}

Related

How to make the console accept input from the Enter key only?

I'd like to make the C# console only accept input from the Enter key on the startup screen.
I've made it so that it closes the console when anything but the Enter key is pressed.
How can I make it so that the console only accepts input from the Enter key so that the application doesn't close when I press anything else, and then receive normal input afterwards?
class Program
{
public static void ClearKeyBuffer()
{
while (Console.KeyAvailable)
Console.ReadKey(true);
}
public static void Main (string[] args)
{
int attempts = 0;
int displayattempts = 5;
bool validentry;
Console.WriteLine("Please press enter to begin");
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
while (attempts < 5)
{
string input;
attempts = (attempts + 1);
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
Console.Clear();
Console.WriteLine("Please enter your user number.");
Console.WriteLine("Attempts Remaining:" + displayattempts);
ClearKeyBuffer();
Console.WriteLine(" ");
input = Console.ReadLine();
{
if (input == "5573")
{
validentry = true;
}
else
{
validentry = false;
}
if (validentry == false)
{
displayattempts = (displayattempts - 1);
Console.Clear();
Console.WriteLine("Error: Invalid number ID entered. Please wait 5
seconds, and try again.");
Thread.Sleep(5000);
}
else if (validentry == true)
{
Console.Clear();
Console.WriteLine("Welcome Samuel");
ValidUserEntry();
}
}
}
}
if (displayattempts == 0)
{
Console.Clear();
Console.WriteLine("Error: You have entered the wrong number ID too many times.
This system will now close in 5 seconds...");
Thread.Sleep(5000);
Environment.Exit(0);
}
}
public static void ValidUserEntry()
{
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("What would you like to do?");
Console.ReadLine();
}
}
Add this line before first if. Then remove if statement and the var key... line.
while (Console.ReadKey(true).Key != ConsoleKey.Enter);
Alternative, more verbose version:
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key.Key != ConsoleKey.Enter);

C# listening to keys and output the results

I've the following code to output Meow or Awo according to the key I press.
It is working but for some reason after the first iteration of do/while I need to press twice on either c and d in order to make it output anything. Any ideas of how I can do it in a different way?
using System;
namespace Program
{
interface Animal
{
void animalSound();
}
class Dog : Animal
{
public void animalSound()
{
Console.WriteLine(" Awo Awo!");
}
}
class Cat : Animal
{
public void animalSound()
{
Console.WriteLine(" Meow");
}
}
class Program
{
static void Main(string[] a)
{
Dog myDog = new Dog();
Cat myCat = new Cat();
Console.WriteLine("--------Press C to call the Cat--------");
Console.WriteLine("--------Press D to call the Dog--------");
Console.WriteLine("Press double ESC to close the program");
do
{
Console.WriteLine("Starting the do loop 1");
ConsoleKeyInfo KeyInfo = Console.ReadKey(true);
while (!Console.KeyAvailable)
{
Console.WriteLine("Starting the while loop 2");
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.animalSound();
} else if(KeyInfo.Key == ConsoleKey.D) {
myDog.animalSound();
}
Console.WriteLine("Breaking the while loop 3");
break;
}
Console.WriteLine("Continue the do loop 4");
continue;
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
}
wants a second entry from
Console.ReadKey(true).Key
user in your loop condition
Try This:
Dog myDog = new Dog();
Cat myCat = new Cat();
Console.WriteLine("--------Press C to call the Cat--------");
Console.WriteLine("--------Press D to call the Dog--------");
Console.WriteLine("Press double ESC to close the program");
ConsoleKeyInfo KeyInfo;
int counter = 1;
do
{
KeyInfo = Console.ReadKey(true);
Console.WriteLine("Starting the while loop " + counter);
counter++;
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.animalSound();
}
else if (KeyInfo.Key == ConsoleKey.D)
{
myDog.animalSound();
}
} while (KeyInfo.Key != ConsoleKey.Escape);
I managed to solve my little problem by changing the code like that:
I removed the first do and last while and kept only one while() with the condition needed
KeyInfo = Console.ReadKey(true);
while (KeyInfo.Key != ConsoleKey.Escape)
{
animal = GwtAnimal(KeyInfo);
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.AnimalSound();
}
else if (KeyInfo.Key == ConsoleKey.D)
{
myDog.AnimalSound();
}
KeyInfo = Console.ReadKey(true);
}

Stuck in creating a simple HW Project

I am completely new to programming, and my professor for my intro cs class gave us a project to create a menu using c# while being able to pick 2 games to play. I decided to go for a math game however I am stuck with a problem that part of my code does not read and I wonder why?
private static void FindTheAnswer()
{
Console.WriteLine("Find the Answer Math Game");
Console.WriteLine("1. 12x = 3");
Console.WriteLine("Choose the Answer: ");
Console.WriteLine("1) 1/4 ");
Console.WriteLine("2) 4 ");
Console.WriteLine("3) 12x-3 ");
Console.WriteLine("1) 3-12x");
string userValue = Console.ReadLine();
if (userValue =="1/4")
// ...
}
I expect the program to ask me these lines :
"Find the Answer Math Game"
"1. 12x = 3"
"Choose the Answer: "
However, it only reads up to "1. 12x = 3" and whatever answer I enter to from the codes I inputted does not read it and it constantly repeats the menu.
Complete Code I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MainGameMenu
{
class Program
{
static void Main(string[] args)
{
//when you do not know how many times to itterate upfront
bool displayMenu = true;
while (displayMenu == true)
{
displayMenu = MainMenu();
}
}
private static bool MainMenu()
{
Console.WriteLine("Choose an option: ");
Console.WriteLine("1) Option 1");
Console.WriteLine("2) Option 2");
Console.WriteLine("3) Exit");
string result = Console.ReadLine();
if (result == "1")
{
FindTheAnswer();
return true;
}
if (result == "2")
{
FindTheLoot();
return true;
}
if (result == "3")
{
return false;
}
else
{
return true;
}
}
private static void FindTheAnswer()
{
Console.WriteLine("Find the Answer Math Game");
Console.WriteLine("1. 12x = 3");
Console.WriteLine("Choose the Answer: ");
Console.WriteLine("1) 1/4 ");
Console.WriteLine("2) 4 ");
Console.WriteLine("3) 12x-3 ");
Console.WriteLine("1) 3-12x");
string userValue = Console.ReadLine();
if (userValue == "1/4")
{
string message = "The Answer is Correct!";
Console.WriteLine(message);
}
else if (userValue == "4")
{
string message = "Incorrect Answer";
Console.WriteLine(message);
}
else if (userValue == "12x-3")
{
string message = "Incorret Answer";
Console.WriteLine(message);
}
else if (userValue == "3-12x")
{
string message = "Incorrect Answer";
Console.WriteLine(message);
}
else
{
string message = "Sorry, We didn't understand.";
Console.WriteLine(message);
}
Console.ReadLine();
}
private static void FindTheLoot()
{
Console.WriteLine("Select the Number that Matches");
Console.ReadLine();
}
}
}
This worked for me
Console.WriteLine("Find the Answer Math Game");
Console.WriteLine("1. 12x = 3");
Console.WriteLine("Choose the Answer: ");
Console.WriteLine("1) 1/4 ");
Console.WriteLine("2) 4 ");
Console.WriteLine("3) 12x-3 ");
Console.WriteLine("1) 3-12x");
string userValue = Console.ReadLine();
if (userValue =="1/4")
Console.WriteLine("correct");
else
Console.WriteLine("wrong");

How get out from class

I have created a small project . and here is it:
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
Console.WriteLine("1 to go to Data Files ");
Console.WriteLine("type quit to exit");
string input = Console.ReadLine();
if (input == "1")
{
Data go = new Data();
}
else if (input == "quit")
{
}
}
}
When user type quit. I want my program to exit. anyone help me, please
You just need something like this:
else if (input == "quit")
{
return;
}
Update: based on your comments I think you're looking for something like this:
class Program
{
public static void Main()
{
while(true)
{
Console.WriteLine("Welcome");
Console.WriteLine("1 to go to Data Files ");
Console.WriteLine("type quit to exit");
string input = Console.ReadLine();
if (input == "1")
{
Data go = new Data();
}
else if (input == "quit")
{
return;
}
else
{
Console.WriteLine("invalid option");
}
}
}
}
You just can use Environment.Exit(code). where code is integer representation of standard application-exit-codes like return 0 or return 1 in world of C++.

How to make number Count in loop in c#?

This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}

Categories

Resources