What would be the best way to exit an application when a user types x without having to hit enter. The current code I am using is this:
Console.WriteLine("\nType x to exit > ");
string test = Console.ReadLine();
while (test != "x")
{
Console.WriteLine("\nType x to exit > ");
test = Console.ReadLine();
}
This will make the user experience better.
You can use Console.ReadKey instead.
Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.
Console.ReadKey() let you read a single key press. Console.readLine() is waiting for a line termination. Here's the doc for reference:
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
You can read the first character and then if it's not "x", read a line input (and prepend the first char received before).
You could do something like this:
do
{
Console.WriteLine("\nType x to exit > ");
}
while (Console.ReadKey().KeyChar != 'x');
Related
I'm trying to make a program which has two options based on the key is pressed by the user, it'will execute a different action. The second option has to do to displaying some information about operations performed in the first option. The main point is to try to make a navigation menu that the user can come back to the main menu through pressing "ESC" or "Enter" to continue in whatever he chooses
Console.WriteLine("\nCAMPAIGN 2022\nSelect what you want to consult:\n1) Votin Urn\n2) DataBase"); // to make clear, database will display info about votes quantity
int options = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("----------------------");
if (options == 1)
{
ConsoleKeyInfo menu;
Console.WriteLine("\nVOTING URN");
while (exit == false)
{
Console.WriteLine("\nSelect your vote:\n1) Jair Bolsonaro;\n2) Luiz
Inacio Lula da Silva;\n3) White;\n4) NulL");
vote = Convert.ToInt32(Console.ReadLine());
while (vote != 1 & voto != 2 & vote!= 3 & vote != 4)
{
if (increment == 0)
{
Console.WriteLine("\nInvalid Vote. Try again:");
}
vote = Convert.ToInt32(Console.ReadLine());
increment += 1;
The thing is: i'm using an if statement and because of local scope when the user selects option 2, to know who have more votes for example, the value is gonna be 0. I tried using switch but it's the same thing. What can I do?
Also, when the user press "ESC" to come back to select "Voting Urn" or "Database" the first letter of the text displayed is cut, like instead of "Campaign" it's "ampaing". I'm using the ConsoleKeyInfo:
Console.WriteLine("Press \"Enter\" to continue or \"Escape\" to return to the main menu");
menu = Console.ReadKey();
if (menu.Key == ConsoleKey.Escape)
{
exit = true;
}
if (menu.Key == ConsoleKey.Enter)
{
exit = false;
}
I would put the while loop so it covers the menu aswell and then just add another choice that is "Go back to main menu / exit application" in a swtich statement. And then have everything inside that switch statement and maybe do some fucnctions like TotalVotes() and Vote().Then do create variable names with each person you can vote for and just ++ each variable inside an if statement if they get a vote. Also this is probably a typo? "voto != 2". It seems like your structure is making it harder that it has to for you.
I'm very new to C# and have started to create a little text-based game in the console before I get into the more technical stuff. On my start menu, I was looking to make a simple flashy 'Press Enter to continue', which loops on and off until the user presses Enter.
while (!enter)
{
WhiteText();
Console.SetCursorPosition(47, 15);
Console.WriteLine("[Press 'Enter' to start game]");
System.Threading.Thread.Sleep(2000);
BlackText();
Console.SetCursorPosition(47, 15);
Console.WriteLine("[Press 'Enter' to start game]");
System.Threading.Thread.Sleep(1000);
}
Essentially I want that repeating while I check if the user has actually pressed enter. I used an if statement with ConsoleKeyInfo input = Console.ReadKey(); which then checks if they've pressed enter. My problem is that I can't seem to get both to run together. Is this something that's even possible in the console.
I'm really hoping I made this clear with my limited knowledge, any help or insight on this would be very appreciated.
You can use Console.KeyAvailable before reading the key.
But when the user presses enter the input will be processed only after the end of the Thread.Sleep . So it'll feel slow to the user
bool show = true;
while (true)
{
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
break;
}
Console.ForegroundColor = show ? ConsoleColor.White : ConsoleColor.Black;
Console.SetCursorPosition(47, 15);
Console.WriteLine("[Press 'Enter' to start game]");
System.Threading.Thread.Sleep(show ? 2000 : 1000);
show = !show;
}
I want to make a little game. The program will output numbers in a loop, and the person has to stop the loop in the exact number that was specified before, by clicking the 'enter' key. like so:
static void Main(string[] args)
{
Console.WriteLine("try to click the 'enter' button when the program shows the number 4");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
//here will be the command which reads the enter key and stops the loop
}
}
One of the users told me to use this code:
Console.WriteLine("try to click the 'enter' button when the program shows the number 4");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
if (e.KeyChar == (char)13)
{
break;
}
}
The problem is, when i use this code, i have an error which says 'the name 'e' does not exist in the current context'.
What does that mean?
Thanks in advance.
There are two basic methods for reading console input:
Console.ReadLine() will pause and wait for the user to enter text followed by the enter key, returning everything entered before the enter key is pressed as a string.
Console.ReadKey() will wait for a keypress and return it as a ConsoleKeyInfo structure with information on the key pressed, what character (if any) it represents and what modifier keys (ctrl, alt, shift) were pressed.
If you don't want to wait until the user presses a key you can use the Console.KeyAvailable property to check if there is a keypress waiting to be read. This can be used in a timing loop to provide a timeout for key entry:
DateTime endTime = DateTime.Now.AddSeconds(10);
while (DateTime.Now < endTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Enter)
{
// do something with key
//...
// stop waiting
break;
}
}
// sleep to stop your program using all available CPU
Thread.Sleep(0);
}
I found a basic idea for a solution to your problem here.
In this answer he is using the Console.KeyAvaliable property to check if a Key has been pressed and then checks if the press key is the one you are lookig for.
To fit it to your needs you have to change it like so:
static void Main (string[] args)
{
Console.WriteLine ("try to click the 'enter' button when the program shows the number 4");
int counter = 0;
int limit = 100000;
do {
while (counter < limit && !Console.KeyAvailable) {
Console.WriteLine (counter);
counter++;
}
} while (Console.ReadKey (true).Key != ConsoleKey.Enter);
}
Try:
ConsoleKeyInfo cki;
do
{
cki = Console.ReadKey();
//What you need to do code
} while (cki.Key != ConsoleKey.Enter);
Console.ReadKey() will wait for a keypress and return it as a ConsoleKey, you just catch and test if it's your desired key.
Trying to make a basic ATM program for my C# class.
In short, the program has 4 accounts which have integer values stored already. The program must display first what action the user would like to take (Display balance, Withdraw, Transfer), then take the user to selected menu and be allowed to perform whatever tasks they wish within the program.
Just having problems with my Display Balance menu. Want to ask if the user would like to display another balance, and restart the Display Balance menu section(The code section here). Here is what I have:
if (ACCselect == 1)
{
string yesno1 = " ";
int dispSEL = 1;
Console.WriteLine();
Console.WriteLine("$$$===Display Balance===$$$");
Console.WriteLine();
Console.WriteLine("\t 1) Savings Account");
Console.WriteLine("\t 2) Debit Card Account");
Console.WriteLine("\t 3) Credit Card Account");
Console.WriteLine("\t 4) Investment Account");
Console.WriteLine();
Console.Write("Select account with 1-4: ");
dispSEL = int.Parse(Console.ReadLine());
DisplayBalance(dispSEL);
Console.WriteLine();
Console.Write("Would you like to select another account? (y/n): ");
yesno1 = Console.ReadLine();
if (yesno1.ToUpper() == "Y")
{
yesno1a = true;
}
else
{
Main();
}
} while (yesno1a == true)
This is part of Main(). ACCselect refers to the selection the user makes, whether they want Display Balance, Withdraw, etc.
The DisplayBalance() method selects the appropriate integer value from an array and displays the corresponding balance.
How can I get my program to repeat this section of code if the user selects "y"?
If the user selects "n" it loops back to the top of the Main() method alright.
Any help would be super helpful.
I'm answering this because I did a similar thing in my first year, and I made similar mistakes.
First, you are calling Main in order to "jump" to the beginning of Main. That works, but it gives you nested calls to Main. Main has become recursive. Once you exit the inner Main invocation, you will jump to the outer Main which is still running. Try answering "n" and then try to exit the program. You will have to exit twice.
If you want to repeat an action until a condition is true, you can use this pattern:
while(true) { //loop forever
if (SomeCondition()) break; //exit
else {
DoStuff();
}
}
Applied to your problem, it goes like this:
while(true) { //loop forever
dispSEL = int.Parse(Console.ReadLine());
DisplayBalance(dispSEL);
Console.Write("Would you like to select another account? (y/n): ");
yesno1 = Console.ReadLine();
if (yesno1 == "n") break; //exit
else continue; //next loop iteration
}
Hope that helps. Feel free to ask follow-up questions in the comments.
My program is a Windows Form Application in C#.
I have an interpreter/compiler IDE w/c basically runs a custom Language through a customized console window.
When interpreting input lines like "scanf", how do pause the interpreting while the user doesn't press enter?
Sample custom code to parse:
1 VAR x AS INT
2 START
3 INPUT: x
4 OUTPUT: x
5 STOP
For example, in those lines, when my program processes line 3, it doesn't process the other lines until the user inputs something and presses enter.
Pseudo-Snippet for line by line parsing:
foreach (string line in inputCode)
{
LineType lineType = line.getType();
if(lineType.InputStatement)
{
//wait for input here
}
else if(lineType.OutputStatement)
{
//analyze output code here
}
else if(lineType.AssignmentStatement)
{
//do Evaluation here
}
}
Console.Readline or Console.ReadKey will allow you to read input from the console simillar to scanf.
You should make each method raise an event to fire the next line.
The INPUT method should fire that event after the user presses enter.