C# - Use ReadKey for loop - c#

I have been searching the web for about an hour and I just can't find the answer to my question. I'm very new to programming and I hope I'm not wasting your time. I want my program to loop if I would click "Y", exit if I click "N" and do nothing if I click any other button. Cheers!
Console.Write("Do you wan't to search again? (Y/N)?");
if (Console.ReadKey() = "y")
{
Console.Clear();
}
else if (Console.ReadKey() = "n")
{
break;
}

You have an example here of Console.ReadKey method :
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
//Get the key
var cki = Console.ReadKey();
if(cki.Key.ToString() == "y"){
//do Something
}else{
//do something
}

You are missing keystrokes this way. Store the return of Readkey so you can split it out.
Also, comparison in C# is done with == and char constants use single quotes (').
ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;
if (key == 'y')
{
Console.Clear();
}
else if (key == 'n')
{
break;
}

you can use the keychar to check that character is pressed
Use can understand that by following example
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}

Presumably by "do nothing" you intend that the user be asked to try pressing a valid key until they do. You can use a do statement (a.k.a. do loop) to repeat some code while some condition is true, for example:
var validKey = false;
var searchAgain = false;
do
{
Console.Write("Do you want to search again? (Y/N): ");
string key = Console.ReadKey().KeyChar.ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine();
if (key == "y")
{
validKey = true;
searchAgain = true;
}
else if (key == "n")
{
validKey = true;
searchAgain = false;
}
else
{
Console.WriteLine("Please press the 'Y' key or the 'N' key.");
}
} while (!validKey);
// Now do something depending on the value of searchAgain.
I used the "not" in !validKey because it reads better that way: do {this code} while (the user hasn't pressed a valid key). You might prefer to use a while loop if you think the code reads better with that construction.
The .ToLower(System.Globalization.CultureInfo.InvariantCulture) bit is so that it doesn't matter if "y" or "Y" is pressed, and it has a very good chance of working with any letter, even the ones that have unexpected upper/lower case variations; see Internationalization for Turkish:
Dotted and Dotless Letter "I" and What's Wrong With Turkey? for explanation of why it's a good idea to be careful about that kind of thing.

Related

Use infinite loop to restart program on any key press and to leave loop on specific key press

I currently have user entering a value for temperature and am giving recommendation based on temperature. I would like to setup a loop to ask the user for input until the user presses either "N" or "n".
For example:
//user input
//temp recommendation
//Continue? Press any key, N or n to exit.
Any key pressed would again ask for user input and N or n would result in program thanking user on screen no longer showing temp recommendation. Professor suggested we use additional method to achieve expected result.
Current incorrect code:
Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
{
if (Console.ReadKey().Key == ConsoleKey.N)
else if (Console.ReadKey().Key == ConsoleKey.n)
return;}
}
Console.WriteLine("Thank you");
You can make use of a local variable in a while loop as follows:
static void main(string[] args)
{
bool keepGoing = true;
while (keepGoing)
{
DoYourWork();
Console.WriteLine("Continue? Press any key to continue, N or n to exit:");
var userWantsToContinue = Console.ReadLine();
keepGoing = userWantsToContinue?.ToUpper() != "N";
}
}
You can use break to exit from loop
while(true)
{
//process temperature conversion
Console.Write("Continue? Press any key to continue, N or n to exit:");
if (Console.ReadKey().Key == ConsoleKey.N)
{
break;
}
}
Enter the do..while loop :)
private static void DoWhatever(string data)
{
// process your temp
}
// inside main somewhere
Console.WriteLine("Enter temp:");
do
{
var temp = Console.ReadLine();
DoWhatever(temp);
Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
}while(Console.ReadKey().Key != ConsoleKey.N);
Console.WriteLine("Thank you");

How to write a string using readkey inside a loop?

I am making a program in which I need the user input to be invisible, and I read that var key = System.Console.ReadKey(true); does just that.
To do what I need, however I need a string with multiple characters, so what I've done is
string Choice1=null;
User1Input:
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
break;
}
Choice1 += key;
}
What is happening is that key simply doesn't read anything, because even if I press enter, the loop does not close.
So your sole intention is to hide the character while user types input in console. In that case you are in right track and your posted code looks good except the last line which says Choice1 += key;. It should be
Choice1 += key.KeyChar;
Your posted code with bit modification
string choice1=null; //casing of variable names
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
break;
choice1 += key.KeyChar;
}

How do you exit an application with a press of a specific key?

I'm doing a small c# application.
(Press 0 to end the program)
All I know is:
Console.ReadKey(); but that only works when you press ANY key.
But how do you exit an application with just 0?
you don't need to run the while loop to findout the key.
you have to compare with the what ever users enters the key.
ConsoleKeyInfo info= Console.ReadKey();
if (info.KeyChar == 48)
Environment.Exit(0);
else
{ // do your things
}
First of all your program will run in a while loop. Read the entered word and check in if condition that whenever it is 0 or not. If it is 0 then let the program finish by breaking the loop otherwise use continue. Let me know if you have any confusion.
You can use while loop :
ConsoleKeyInfo cki = new ConsoleKeyInfo();
while (cki.Key != ConsoleKey.D0 && cki.Key != ConsoleKey.NumPad0)
{
cki = Console.ReadKey(true);
// your code here
}

How do I nullify (or assign another value to) a System.ConsoleKey value once it's finished being used?

I have a repeating code here, full of goto statements that make this while loop well... Repeat forever.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
main();
}
public static ConsoleKeyInfo keyPressed;
private static void main()
{
start:
keyPressed = Console.ReadKey();
while (true)
{
loopstart:
if (keyPressed.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed the Enter Key!");
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed the Escape Key!");
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Spacebar)
{
Console.WriteLine("You pressed the Spacebar!");
goto loopstart;
}
else
{
break;
}
}
Console.WriteLine("You broke the loop!");
goto start;
}
}
}
Without removing any code, is it possible to change the value of keyPressed.Key or keyPressed itself to NULL; the state it was when it was declared, or to any other value/key that's not the spacebar, enter or escape key?
Of course, the problem could be solved by removing all the goto loopstart; in the code, but that's against the point of the question.
What I want to do is make the keyPressed.Key value NULL (or any other value) so that all the IF statements will result in false, which therefore means not running the goto loopstart code.
The problem now is that when I try to nullify it with a simple keyPressed = null;, it comes with the error of:
Cannot convert null to 'System.ConsoleKeyInfo' because it is a non-nullable value type.
Is there any way I can nullify (or change the value to something else) so that I can break the loop?
(As in: Make the IF statement get to the point where it has to run the else code)
It should look something like:
...
{
loopstart:
if (keyPressed.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed the Enter Key!");
// keyPressed = null; <-- Does not work.
// Do something to make ConsoleKey.Key to equal something else.
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed the Escape Key!");
...
Obviously with the // Do something to make ConsoleKey.Key to equal something else. replaced with working code?
If this works, the first time the loop runs (presuming the key pressed at the start is either the Spacebar, Escape or Enter keys) would result with the goto loopstart; being used, and the second time round would skip through to the goto start; where it'll ask for another key.
And then the process repeats at the speed of which the user gives an input, rather than repeating with the same key without stop, or asking for another key.
Basically: Make the loop run the IF statement as a proper IF statement instead of a FOR loop.
See also
Why use goto-statement, it's very outdated constructure. You can easily continue the loop. And else check is also redundant. You can simply read the key from Console before check, like this:
while (true)
{
keyPressed = Console.ReadKey();
switch (keyPressed.Key)
{
case ConsoleKey.Enter:
Console.WriteLine("You pressed the Enter Key!");
continue;
case ConsoleKey.Escape:
Console.WriteLine("You pressed the Escape Key!");
continue;
case ConsoleKey.Spacebar:
Console.WriteLine("You pressed the Spacebar!");
continue;
}
// should be outside the switch for breaking the loop
break;
}
If you want to clear keyPressed, use default construction, like this:
keyPressed = default(ConsoleKeyInfo);
But why do you want to do this? Garbage Collection will clear the memory by itself, you should not go into there.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
main();
}
public static ConsoleKeyInfo keyPressed;
private static void main()
{
start:
keyPressed = Console.ReadKey();
while (true)
{
loopstart:
if (keyPressed.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed the Enter Key!");
keyPressed = new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false);
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed the Escape Key!");
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Spacebar)
{
Console.WriteLine("You pressed the Spacebar!");
goto loopstart;
}
else
{
break;
}
}
Console.WriteLine("You broke the loop!");
goto start;
}
}
}

Which loop do I use to ask if a user wants to continue the program in C#

I made a program that asks for input and returns a value. After, I want to ask if the user wants to continue. But I don't know what to use.
You want to use a do / while loop, or an infinite while loop with a conditional break.
A do-while loop is often used:
bool #continue = false;
do
{
//get value
#continue = //ask user if they want to continue
}while(#continue);
The loop will be executed once before the loop condition is evaluated.
This only allows 2 keys (Y and N):
ConsoleKeyInfo keyInfo;
do {
// do you work here
Console.WriteLine("Press Y to continue, N to abort");
do {
keyInfo = Console.ReadKey();
} while (keyInfo.Key != ConsoleKey.N || keyInfo.Key != ConsoleKey.Y);
} while (keyInfo.Key != ConsoleKey.N);
I would use a do..while loop:
bool shouldContinue;
do {
// get input
// do operation
// ask user to continue
if ( Console.ReadLine() == "y" ) {
shouldContinue = true;
}
} while (shouldContinue);
You probably want a while loop here, something like:
bool doMore= true;
while(doMore) {
//Do work
//Prompt user, if they refuse, doMore=false;
}
use Do While Loop. something similar will work
int input=0;
do
{
System.Console.WriteLine(Calculate(input));
input = GetUserInput();
} while (input != null)
Technically speaking, any loop will do it, a for loop for example (which is another way to write a while(true){;} )
for (; true; )
{
//Do stuff
if (Console.ReadLine() == "quit")
{
break;
}
Console.WriteLine("I am doing stuff");
}

Categories