This question already has answers here:
Listen on ESC while reading Console line
(6 answers)
Closed 1 year ago.
first time posting here, so I apologise in advance in case I miss something important, please let me know if that's the case!
I'm writing a console application that has a menu with several different options in different layers, and I'm trying to make a function that will, at any time as the user works in these menus, notice if the Esc key is pressed. To make my code less cluttered I wrote a separate method that I can simply call at any point when I'm asking for input (like a choice, or entering information into a form, or such).
The problem I have is that it always cancels out the first key press. If a user enters a number to move in the menu, the number doesn't get entered, if they enter a name into a form the first letter is missing etc.
Is there a way around this?
The code currently looks like this;
public static void checkForEsc()
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Escape)
{
switch (currentUserisAdmin)
{
case true:
Menu.AdminMenu();
break;
case false:
Menu.CustomerMenu();
break;
}
}
}
Thanks in advance :)
Edit:
Might be worth adding that the code where this snippet gets called looks something like this, with very small variations;
Console.WriteLine($"1. Add a user\n2. Remove a user \n3. See user info \n \n9. Cancel");
Program.checkForEsc();
int response2 = CheckIfResponseInt(Console.ReadLine());
You need to write your own line editor instead of using Readline. It's described in the link below. You may need to add support for other control keys such as backspace or add a check that only numeric keys are being pressed.
Listen on ESC while reading Console line
I am trying to build a quiz game using alexa.net. However i´ve run into a potential problem.
Whenever the user has answered a question and the answer has been evaluated i want to immediately ask another question.
As it is right now, the user has to manually request another question. What i would like to have happen, was that the intent that handles the question keeps calling itself until the user actively chooses to end the game.
Is that even possible? If so, can anyone point me in the right direction, maybe even write up a brief hello-world style example?
Suppose you want to create a math quiz game where Alexa will ask you random math questions and you have to provide the right answer. The game has to continue until the user ask specifically to quit.
Create an AnswerIntent which is triggered when the user says an answer. Our answers are numbers, so create this intent with AMAZON.NUMBER slot which lets you capture the numbers spoken. (Choose your slot according to the answers for your questions).
Sample utterance for AnswerIntent:
{number}
the answer is {number}
is it {number}
{number} -> AMAZON.NUMBER slot
So each time when the user says an answer to your question you will receive a POST request in your backend with the intent triggered (in this case AnswerIntent), slot and its value. Then:
Validate the answer.
Update the score (if at all your usecase has a score)
Generate the next question.
Provide a response with the next question.
You will only receive a request at your backend when there is a user interaction. So make sure that when the user says an answer, your response has the next question to asked. In this way the user can continue answering questions without asking for a question explicitly.
Sample Interaction:
User : Alexa, open math quiz
Alexa: Welcome to math quiz. Here is your first question.
What is the sum of five and four.
[you will receive the launch request and your response has the first question]
User : Nine
[you will receive AnswerIntent request, with number slot having value 9.
Validate the answer and generate the next question]
Alexa: Correct!. Here is your next question.
What is the product of ten and five.
User : Twenty.
Alexa: Wrong, the right answer is fifty.
here is your next question.
What is sum of two and six.
User : Stop
[AMAZON.StopIntent is triggered and you can now end the game.]
Alexa: Bye.
Use sessionAttributes to store some information about the question or its answer so that you can validate it easily at the backend when your receive a response from the user.
Starting my Intro To Programming class and we'll be using C# throughout it. I'm currently writing a practice program to get familiar with C# that asks the user for their name and age and then reads it out to them and asks if it is correct. I want to make it so that if the user wants to change their inputted data for any reason then they can press the "n" key for "no that's not right" and re enter their data. However, I want to re-ask them the questions for their age and name(separately) without having to re-type the code block with the Console.WriteLines and if...else block. I did some research and found that:
the "go-to" statement was made by the devil himself and it's essentially the programming equivalent of a hate crime if I use it
making a new method (and subsequently calling that method in my code) with the block of code asking the question seems to be the way to go about it.
My problem is that while I've (hopefully) figured out that's what I need to do, I can't seem to figure out how exactly to either implement that method nor call it correctly later on.
here is the method I'm trying to create that I want to hold an "if...else" statement asking if the info is correct, incorrect, or re-ask the question if the enter something other than "y" or "n":
public void Question()
{
Console.Write("Could I get your name? (Press enter when you are done) ");
string user_name = Console.ReadLine();
Console.Clear();
Console.Write("Awesome! Now if you could just enter your age: ");
string user_age = Console.ReadLine();
Console.Clear();
Console.WriteLine("So according to the information I have on file here... you are " + user_name + " and you're " + user_age + " years old....");
}
This isn't homework so I don't mind specific pieces of code so I can see how it works and tinker with it to learn :)
Good work on doing some research on your own, and a fairly decent question. And you're on the right track.
So let's first focus on asking the question part. If you look at your Question() method, you can see that you're sort of doing the same thing repeatedly inside it. Yes you're asking different questions, but essentially you're doing three things:
Ask a question.
Get the answer.
Clear the Console.
So, maybe you can put those three things into one method, and the only thing that's variable here is the question, so you can pass the question as a parameter.
static string AskQuestion(string question)
{
Console.Write(question);
var ans = Console.ReadLine();
Console.Clear();
return ans;
}
Alright, a bit better.
Now, how do we repeatedly ask the user a question until we get a satisfactory answer? Loops are a good solution, and particularly either while or do-while which doesn't iterate a set number of times but rather until a condition is fulfilled. I personally like to use do-while in a situation like this.
So what do we have to do there now? Let's break it down. We will write a function, and inside a loop we want to:
- Ask a question and get the answer. Good thing we have a method that does just that.
- Show the user the answer he/she entered.
- Ask the user to confirm if it's good.
- If yes, terminate the loop, and return the answer.
- If not, ask the question again.
Something that looks like this:
static string GetSatisfactoryAnswer(string question)
{
var ans = string.Empty;
bool goodAns = false;
do
{
ans = AskQuestion(question);
Console.WriteLine("You entered {0}. Is that correct?", ans);
var confirm = Console.ReadLine();
if (confirm.ToLower() == "y")
goodAns = true;
} while (!goodAns);
return ans;
}
Now you can call them like this:
static void Main(string[] args)
{
var name = GetSatisfactoryAnswer("Could I get your name? (Press enter when you are done) ");
var age = GetSatisfactoryAnswer("Awesome! Now if you could just enter your age: ");
Console.WriteLine();
Console.WriteLine("Name : {0}", name);
Console.WriteLine("Age : {0}", age);
Console.ReadLine();
}
NOTES
This is only to give you a rough idea, you'll need to do a lot of error handling. Such as, what if the user enters anything other than Y/N for the confirmation?
It's always a good idea to actually get the age as an integer. So use int.TryParse() to convert the string input into an int and then do something about it if a non-numerical value was entered.
In your example, you get both Name and Age at once, then asks use to confirm them later. In my opinion, it's best to finish one thing and start another. In other words, make sure your got a satisfactory answer to Name, then move onto Age, etc. My answer is designed that way.
Hope this helps. Good luck!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Thanks to those who replied, your solutions were spot on !
# to the messageboard ..apologies for overloading the question and not being specific.
I have been experimenting with what I have been given as solutions and in order to keep things consistent as per the solutions offered I have the following code:
var mystr = String.Format("{0},{1:yyyy,M,d,H,m,s},{2:yyyy,MM,dd,HH,mm,ss},{3},{4},{5},{6},{7},{8},{9},{10}",
this.textBox3.Text, //0
this.dateTimePicker1.Value,//1
this.dateTimePicker2.Value,//2
Convert.ToInt32(this.checkBox1.Checked),//3
Convert.ToInt32(this.checkBox2.Checked),//4
Convert.ToInt32(this.checkBox3.Checked),//5
Convert.ToInt32(this.checkBox4.Checked),//6
Convert.ToInt32(this.checkBox5.Checked),//7
Convert.ToInt32(this.checkBox6.Checked),//8
Convert.ToInt32(this.checkBox7.Checked),//9
Convert.ToInt32(this.checkBox8.Checked));//10
textBox1.Text = mystr;
MessageBox.Show("The value entered is: " + mystr , " Alarm DATA", MessageBoxButtons.OK);
On clicking an OK button I have a string of values namely :
88,2015,5,17,22,6,53,2015,05,17,22,06,53,0,0,0,0,0,0,0,0
I am going to be sending these to an Arduino via serial, the problem is the format they are in at the moment.
The arduino is expecting them in the same format (data type) as one would send from the serial terminal window and without a newline character added.
(Which currently is working when I type this 88,2015,5,17,22,6,53,2015,05,17,22,06,53,0,0,0,0,0,0,0,0 into a serial terminal window.
My question is how to I set/change the value of the variable mystr to what the arduino needs ?
I am currently using Serial.parseint() on the Arduino to receive the values separated by commas and load them into variables.
Any help is greatly appreciated.
D
For reference ..Here's my original question:
I have created a Windows form which currently has 9 checkboxes (I
don't know if this was the right choice.) as well as a button and 2
textbox.
At the moment I type dates into the textboxes in the form of
YYYY,MM,DD,hh,mm,ss and then I select checkbox values which when
selected should return a 1 and if un-selected a 0.
I realize this may seem like a very basic question but I can't seem to
find the answers I'm looking for.
I would like the following to happen when I click the button :
A single string get's generated/created. (Eventually I will send this
out via serial. (not sure if this is the variable type I should be
using and I would appreciate and example for both if at all possible).
The string/int/message comprises of the two dates ( or as unix
timestamps or an option for either) and each checkbox value (either a
0 or a 1) << this is where I battling to find info on as well as the
datetime picker)
So the actual string would look something like this :
2015,4,30,3,0,5,2015,4,30,3,0,10,0,1,0,0 (where the format is
date1,date2,checkbox1,checkbox2,checkbox3,checkbox4)
I can currently use the checkbox.text fields but I would prefer to
just get the value from each as a zero or 1 to build my
string/int/message.
I am using C# VS express.
Firstly, I would suggest using a DateTimePicker to enter the date and time. You can have it display whatever format you like and it will handle validation for you, which ensures the user never enters an invalid format or an invalid value. You could then do something like this:
var str = String.Format("{0:yyyy,M,d,H,m,s},{1:yyyy,M,d,H,m,s},{2},{3},{4}",
this.dateTimePicker1.Value,
this.dateTimePicker2.Value,
Convert.ToInt32(this.checkBox1.Checked),
Convert.ToInt32(this.checkBox2.Checked),
Convert.ToInt32(this.checkBox3.Checked));
If you want something more generic, try this:
var dates = this.Controls.Cast<Control>()
.OfType<DateTimePicker>()
.Select(dtp => dtp.Value.ToString("yyyy,M,d,H,m,s"));
var bools = this.Controls.Cast<Control>()
.OfType<CheckBox>()
.Select(cb => Convert.ToInt32(cb.Checked).ToString());
var str = String.Join(",", dates.Concat(bools).ToArray());
That will work with any number of controls with any names. The one caveat is that the z-order of each group of controls must match the order you want their output to appear in the final String. You can adjust the z-order by dragging and dropping in the Document Outline window, which can be opened from the View > Other Windows menu.
string s = null;
if (checkbox.checked)
s = "1";
else
s = "0";
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have discovered that many times I don't need the out parameter of the TryParse method, but the problem that it is necessarily. Here I will show one example when it's not needed.
I want to check if a string is an integer, if it is an integer then print "An integer"; otherwise, print "Not an integer". So here is the code:
string value = Console.ReadLine(); //Get a value from the user.
int num; //Why should I have it?? No need at all !
if (int.TryParse(value, out num))
{
Console.WriteLine("An integer");
}
else
{
Console.WriteLine("Not an integer");
}
I am just wondering why TryParse always returns an out parameter? Why it doesn't have the overload without an out parameter?
Updated Answer:
In more recent versions of C# you can declare the output parameter inline, which allows you to remove the line of code you don't want in your example:
string value = Console.ReadLine(); //Get a value from the user.
if (int.TryParse(value, out int num))
{
Console.WriteLine("An integer");
}
else
{
Console.WriteLine("Not an integer");
}
You can simply ignore the result in your code and no longer have that extra line. You still have the extra parameter, but so?
The underlying "why" is still the same and is unlikely to ever change. The method needed to return two things, a bool indicating success and an int indicating the resulting value if successful. (I can't think of another way to convey the result, can you?) Since a method can only return one thing, and a custom result type seems like overkill for this, the decision was made to return the bool and have the result be an out parameter. And once that decision was made, it has to remain for the duration of the language.
"They" certainly could add an overload that doesn't output in the int value. But why? Why expend the effort in designing, documenting, testing, and as we've seen perpetually supporting a method that serves no purpose but to save a few keystrokes for an extreme minority of developers? Again, very unlikely.
For such features you are certainly welcome to propose a change. It would be pretty cool to have a proposal accepted, I imagine. I doubt this one would be, but if you're passionate about it then by all means have at it.
Original Answer:
The short answer is, "Because that's how the method is defined." Perhaps by chance someone from the C# language team might find this question and provide reasoning into why decisions were made, but that doesn't really change much at this point. C# is a statically compiled language and the method signatures need to match, so that's just the way it is.
(Imagine if they changed this and broke .TryParse() on all existing codebases. That would be... bad.)
You might be able to work around this in your own code, though. Something as simple as an extension method could do the trick for you:
public static bool IsInt(this string s)
{
int x = 0;
return int.TryParse(s, out x);
}
Then in your code you'd just need to call that method from the string value:
string value = Console.ReadLine();
if (value.IsInt())
Console.WriteLine("An integer");
else
Console.WriteLine("Not an integer");
It has the out parameter because the vast majority of the time when people use it, they want the int (or double, or decimal, or datetime, or whatever) that was parsed.
If you don't want/need the parsed value, and you find yourself doing it all the time, you could write your own "wrapper" on .TryParse() that just takes the string.
In this example (and you could make it more generic, I'm sure) you could do something like
public static bool TryParseNoOutput(this string value)
{
int noNeed = 0;
return int.TryParse(value, out noNeed);
}
Then in your code (in this case) you'd call:
string value = Console.ReadLine();
if(value.TryParseNoOutput()) Console.WriteLine("An Integer");
else Console.WriteLine("Not an integer."):
Edit: As has been pointed out in the comments, I tried to call "int.TryParseNoOutput" when I had defined it as an extension on a string. Answer has been updated to reflect that.
TryParse is a relatively complex operation to determine the int representation of a string. If there would be an overload that just returns a bool, it would be very likely that many (unexperienced) developers would follow this inefficient pattern:
int myInt = -1;
if(int.TryParse("123"))
myInt = int.Parse("123");
Why does TryParse have an out parameter?
For the very simple reason of how TryParse is implemented.
The way you determine whether or not something is parsable, is by parsing it! If you are able to parse something, then it is parsable. If you cannot parse it, then it is not parsable.
Therefore, by way of determining if something is parsable or not, if it is parsable, then we have already parsed it! It would be silly to throw away this parsed value (anyone who's wondering whether or not something is parsable is likely interested in the parsed result), so the parsed value is returned.
It has an out parameter because the parsed value is a by-product of a true-returning TryParse call.