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

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

Related

How to get a menu to loop

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

How would you go about refreshing your application once you have pressed any key? C#

I'm currently creating a program; I cannot figure out how to refresh the application after a key is pressed.
So far I have:
Console.WriteLine("Press Any Key To Refresh");
Console.ReadKey();
Full Code Block
class Program
{
static void Main(string[] args)
{
int userInput;
DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
FileInfo[] files = folderInfo.GetFiles();
Console.WriteLine("Welcome To File Manager");
Console.WriteLine("");
Console.WriteLine("Current Folder: C:\\Windows");
Console.WriteLine("");
Console.WriteLine("Please Select An Opion Between 1 To 4:"); // Displays Options for Main Menu.
Console.WriteLine("1. ");
Console.WriteLine("2. ");
Console.WriteLine("3. ");
Console.WriteLine("4. ");
userInput =int.Parse(Console.ReadLine());
{
if (userInput == 1)
{
Console.WriteLine("Files in C:\\Windows:");
for (int index = 0; index < files.Length; index++) // Lists The Files Within The Speficied Folder C:\\Windows - Also Assigns Numerical Value To Each File.
{
Console.WriteLine("{0}" , index + ". " + 1 + files[index].Name + " (" +(files[index].Length) + ")");
}
Console.WriteLine("Press Any Key To Return To Main Menu");
Console.ReadKey();
}
else if (userInput == 2)
{
// code for option 2
}
else if (userInput == 3)
{
// Code for option 3
}
else if (userInput == 4)
{
// Closes Application.
}
} while (userInput != 4);
Once the operation within option (1) has ran, the message; "Press Any Key To Refresh" appears - Afterwards I'd like it to refresh the application once a key is pressed!
I hope this clarifies what I was asking!
Many Thanks
- Dan
This may help if I understood correctly what you want to accomplish.
bool isClicked = true;
while(isClicked)
{
Console.WriteLine("Please Select An Opion Between 1 To 4:");
int userInput = int.Parse(Console.ReadLine());
switch (userInput)
{
case 1:
Console.WriteLine("Press Any Key To Return To Main Menu");
Console.ReadKey();
//isClicked = false; // Used to suspend the operation
break;
case 2:
// code for option 2
break;
case 3:
// code for option 3
break;
case 4:
// code for option 4
break;
default:
Console.WriteLine("Error occured");
break;
}
}

c# console: How to ReadLine without the need of pressing [Enter]

My c# console application is used as a login for my c# form application, the problem is, in my c# console app i haven't been able to figure out a way to ReadLine without the need of pressing Enter because i need to detect whether F2 or Enter is pressed then ReadLine without needing user to press Enter again. For example, if i wanted to detect if F2 is pressed i would need to wait until F2 is pressed until I'm able to ReadLine, Hopefully this question was worded in a way that it makes sense, I'm sure you can tell I'm quite a 'noob' at c#.
Example of my problem:
static void Main()
{
var KP = Console.ReadKey();
if (KP.Key == ConsoleKey.F2)
{
//User Presses F2
}
else if (KP.Key == ConsoleKey.Enter)
{
string UserName = ReadLineWithoutPressingEnter();//Just a example
//ReadLine without needing to press enter again
}
}
Thank you for your time.
Save the result from ReadKey and then just do a ReadLine:
public static void Main(string[] args)
{
var KP = Console.ReadKey();
if (KP.Key == ConsoleKey.F2)
{
return;
}
string UserName = KP.KeyChar + Console.ReadLine();
Console.WriteLine(UserName);
Console.ReadLine();
}
You've already found Console.ReadKey(). That's a start. You'll need to also build a state machine around this function to return a completed string at the end of the line, but this method is the key to making that work. Don't forget to handle things like backspace and delete.
Here is an example Try this
static void Main(string[] args)
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();
int i = 0;
do
{
while (Console.KeyAvailable == false)
Thread.Sleep(250); // Loop until input is entered.
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.F1)
{
Console.WriteLine("User Have Press F1");
//do some thing
}
if (cki.Key == ConsoleKey.Enter)
{
Console.WriteLine("User Have Press Enter");
//do some thing
}
if (cki.Key == ConsoleKey.A)
{
Console.WriteLine("User Have Press A");
//do some thing
}
} while (cki.Key != ConsoleKey.X);
}
This should work
static void Main(string[] args)
{
ConsoleKeyInfo e;
string userName = "";
while (true)
{
e = Console.ReadKey();
if (e.Key == ConsoleKey.Enter)
{
break;
}
else if (e.Key == ConsoleKey.F2)
{
//things to do when F2
}
userName += e.KeyChar;
}
Console.WriteLine("username: " + userName);
Console.Read();
}

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

Saving values within if statement C#

I'm a newbie at C# and I'm having some difficulties writing a program that is going to let you save values in a variable, everything is working fine, except I can't save values into my variable. Here's the code:
while (true)
{
//Menu
Console.WriteLine (" \n\tWelcome!");
Console.WriteLine (" \t[1]Store value");
Console.WriteLine (" \t[2]Write message");
Console.WriteLine (" \t[3]Clear the console");
Console.WriteLine (" \t[4]Shut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32 (Console.ReadLine ());
//Users message
string usrMsg = null;
//if statement
if (choice == 1) {
usrMsg += Console.ReadLine ();
} else if (choice == 2) {
Console.WriteLine (usrMsg);
} else if (choice == 3) {
//Shuts down program
break;
} else if (choice == 4) {
//Clear program
Console.Clear ();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
You just move the usrMsg variable out of while block as a global the value will be saved.
//Users message
string usrMsg = null;
while (true)
{
//Menu
Console.WriteLine(" \n\tWelcome!");
Console.WriteLine(" \t[1]Store value");
Console.WriteLine(" \t[2]Write message");
Console.WriteLine(" \t[3]Clear the console");
Console.WriteLine(" \t[4SShut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32(Console.ReadLine());
//if statement
if (choice == 1)
{
usrMsg += Console.ReadLine();
}
else if (choice == 2)
{
Console.WriteLine(usrMsg);
}
else if (choice == 3)
{
//Shuts down program
break;
}
else if (choice == 4)
{
//Clear program
Console.Clear();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
When this runs it always creates userMsg as null. That means that at best it will 'save' only 1 value when the user chooses '1'. However, this will never get displayed if the user selects '2' as when the user gets to the menu again userMsg will have been set to null again.
My assumption is that you're trying to save the number of times someone has selected '1' and then display that if the user then hits option '2'.
Stick this:
//Users message
string usrMsg = null;
outside of the 'while' loop.

Categories

Resources