Console.ReadLine() alternative - c#

I have the following console application:
private static bool run = false;
static void Main(string[] args)
{
int choice = 0;
while (!run)
{
Console.WriteLine("\n\t\t Press '1', '2' or '3' to continue");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
{
Console.Clear();
Console.WriteLine("\n\t\t you pressed 1");
}
case 2:
{
Console.Clear();
Console.WriteLine("\n\t\t you pressed 2");
}
case 3:
{
Console.Clear();
Console.WriteLine("\n\t\t you pressed 3");
}
default:
{
Console.Clear();
Console.WriteLine("\n\t\t Invalid key");
break;
}
}
}
Console.ReadLine();
}
However, with this code:
choice = int.Parse(Console.ReadLine());
I wish to have it so that when the user pressed the 1 key or 2 or 3, the appropriate code is executed straight away, as opposed to having to press the enter key once you've pressed the desired key. What are some alternatives?
Any help/guidance/tips is greatly appreciated,
Thanks

How about ReadKey then?

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

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

Console application Menu issues in c#

i'm very new to C# (well, programming in general)
I am trying to create a menu for a c# console application. The the menu keeps reappearing after a selection from the menu is made... I've researched and tried many different options but nothing seems to be working for me.... I know it's something stupid that I've done incorrectly.
Any advice or guidance would be very much appreciated. Thanks in advanced.
static void Main() //Start of program
{
//Menu and other UI stuff
int userSelection = 0;
do
{
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write ("Please choose an option 1-3: ");
userSelection = Int32.Parse(Console.ReadLine());
switch(userSelection)
{
case 1:
readFile();
break;
case 2:
decryption();
break;
case 3:
Environment.Exit(0);
break;
default:
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
}
while (userSelection != 4);
}
Your do/while only will stops when your userSelection have value 4, in this example, it never will happen.
change your while condition to
while(userSelection <= 0 || userSelection > 3)
it should solve...
maybe you would like to use something like:
int userSelection = 0;
bool validAnswer = false;
do
{
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write ("Please choose an option 1-3: ");
userSelection = Int32.Parse(Console.ReadLine());
switch(userSelection)
{
case 1:
readFile();
validAnswer = true;
break;
case 2:
decryption();
validAnswer = true;
break;
case 3:
validAnswer = true;
Environment.Exit(0);
break;
default:
Console.Clear();
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
}while (!validAnswer);
It keeps reappearing because you placed your code in a do while loop. If you want to run this code only once don't use looping constructs, just place it directly in Main.
If you use something like
do
{
// ...
}
while (userSelection != 4);
the code inside the loop will be repeated until the user enters 4.
From msdn article on a do while:
The do statement executes a statement or a block of statements
repeatedly until a specified expression evaluates to false.
Another option would be to use a break statement after the switch block.
class Program
{
static void Main() //Start of program
{
//Menu and other UI stuff
string userSelection;
do
{
Console.Clear();
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write("Please choose an option 1-3: ");
userSelection = Console.ReadLine();
switch (userSelection)
{
case "1":
Console.WriteLine("mission 1");
break;
case "2":
Console.WriteLine("mission 2");
break;
case "3":
Environment.Exit(0);
break;
default:
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
Console.ReadLine();
}
while (true);
}
}

Trouble reading only one character from ReadKey()

I'm new to c# and I'm creating a little console application. I want a smooth menu system changing on key inputs. I have a loop registering
public void MainMenu()
{
ConsoleKeyInfo _key;
do
{
Console.WriteLine("Main Menu");
Console.WriteLine("Press 1 for cars");
Console.WriteLine("Press 2 for planes");
Console.WriteLine("Press 3 for boats");
Console.WriteLine("Enter 'q' to exit");
_key = Console.ReadKey();
switch ((char)_key.Key)
{
case '1':
{
Console.Clear();
CarMenu();
break;
}
case '2':
{
Console.Clear();
PlaneMenu();
break;
}
case '3':
{
Console.Clear();
BoatMenu();
break;
}
case 'Q':
{
Environment.Exit(0);
break;
}
default:
{
Console.WriteLine("No options to that key...");
Console.WriteLine("-------------------------\n\n");
break;
}
}
} while (true);
}
public void CarMenu()
{
do
{
Console.Clear();
Console.WriteLine("Car menu");
Console.WriteLine("Press 1 to list all cars");
Console.WriteLine("Press 2 to list single car");
Console.WriteLine("Press 3 to register a new car");
Console.WriteLine("Press 0 for main menu");
Console.WriteLine("Enter 'q' to exit");
_key = Console.ReadKey();
Console.WriteLine((char)_key.Key);
Console.ReadKey();
switch ((char)_key.Key)
{
case '1':
{
Console.Clear();
_handler.listAllDevices();
break;
}
case '2':
{
Console.Clear();
PlaneMenu();
break;
}
case '3':
{
Console.Clear();
BoatMenu();
break;
}
case '0':
{
Console.Clear();
MainMenu();
break;
}
case 'Q':
{
Environment.Exit(0);
break;
}
default:
{
Console.WriteLine("No options to that key...");
Console.WriteLine("-------------------------\n\n");
break;
}
}
} while (true);
}
I have several cases, amongst case '1' and case 'Q'. First time I press any of them it works but next time I need to press 1 twice and q thrice. No matter SHIFT + q or Caps Lock. I tried a number of different solutions, clearing buffers etc but haven't really accomplished much.
Seems strange to me but I guess I'm missing something. Any clues? Thanks
So the full snippet is:
{
private static void Main(string[] args)
{
do
{
Console.WriteLine("Main Menu");
Console.WriteLine("Press 1 for cars");
Console.WriteLine("Press 2 for planes");
Console.WriteLine("Press 3 for boats");
Console.WriteLine("Enter 'q' to exit");
ConsoleKeyInfo _key = Console.ReadKey();
switch ((char) _key.Key)
{
case '1':
{
Console.Clear();
CarMenu();
break;
}
case '2':
{
Console.Clear();
//PlaneMenu();
break;
}
case '3':
{
Console.Clear();
//BoatMenu();
break;
}
case 'Q':
{
Environment.Exit(0);
break;
}
default:
{
Console.WriteLine("No options to that key...");
Console.WriteLine("-------------------------\n\n");
break;
}
}
} while (true);
}
public static void CarMenu()
{
do
{
Console.Clear();
Console.WriteLine("Car menu");
Console.WriteLine("Press 1 to list all cars");
Console.WriteLine("Press 2 to list single car");
Console.WriteLine("Press 3 to register a new car");
Console.WriteLine("Press 0 for main menu");
Console.WriteLine("Enter 'q' to exit");
ConsoleKeyInfo _key = Console.ReadKey();
Console.WriteLine((char) _key.Key);
//Console.ReadKey();
switch ((char) _key.Key)
{
case '1':
{
Console.Clear();
Console.WriteLine("1");
//_handler.listAllDevices();
break;
}
case '2':
{
Console.Clear();
Console.WriteLine("1");
break;
}
case '3':
{
Console.Clear();
Console.WriteLine("1");
break;
}
case '0':
{
Console.Clear();
return;
}
case 'Q':
{
Environment.Exit(0);
return;
}
default:
{
Console.WriteLine("No options to that key...");
Console.WriteLine("-------------------------\n\n");
break;
}
}
} while (true);
}
}
As you can see, I have coomented second call to ReadKey(). This was original problem.

Categories

Resources