Console Keypress not working? - c#

So I'm making a console-based text game to learn more C# but I'm now stuck and have resorted to SO.
This might be an obvious answer but I require another pair of eyes to help me. I've checked the other questions on here and they don't seem to aid me.
In my Main(), I have the following:
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();
NonExplicit();
}
Self explanatory. Once it hits the NonExplicit() method, the following is called:
char yes = Console.ReadKey().KeyChar;
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
What seems to happen is that, when 'y' or 'Y' is pressed:
1) It requires enter to be hit to register the above.
2) It runs both the if & else WriteLines, which I assume is in conjunction with 1)?
How can I amend my code so that when 'y/Y' is pressed, it reads the correct criteria? Or how can I remove the need for Enter to be pressed to proceed?

Used your code below, I tested it and it works.
I moved the char yes = Console.ReadKey() to below the Console.WriteLine().
I changed the name = Console.ReadKey() to Console.ReadLine() because a name is more then 1 key.
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}

In your code, after Console.WriteLine("\nTo proceed, please press any key..."); you have Console.ReadLine(); which expects you to enter a line in the console (not reading till you press enter) and then in your second method, you're trying to read the console again (but this time for a single key).
Wouldn't it help if you remove the first Console.ReadLine() ?
And then you are trying to get the yes/no answer before asking your question (and before doing another ReadKey.

string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
//any thing
}

char yes = Console.ReadKey(); // No need for .KeyChar
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
could be
int age = -1
Console.WriteLine("Before entering the unknown, could you please confirm your age? ");
while (age == -1)
{
if !(int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age");
}
}
name = Console.ReadKey().ToString();
should be
name = Console.ReadLine();
if (yes == 'y' || yes == 'Y')
could be
if (yes.ToUpper() == "Y")

Related

How to do while loop/Do while loop with sentinel value with switch

Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}

C# enter mathematical problem and solve it when user enter "="

I have some test. I need to do and I just can't understand how to do it.
We are asked to make a program that will take the user input (numbers and operators) and will end to take inputs if the user enters "=", then it will solve it.
Example:
user input - 10+10+10+10= (will stop cuz he enterd = and calculate)
will be like that 10+10+10+10=40
int sum;
int num;
char x;
string op;
Console.WriteLine("lets start sum some numbers!");
Console.WriteLine("enter number and than + press = to end and sum all the numbers");
do
{
while (!Console.KeyAvailable)
{
op = Console.ReadLine();
}
} while (Console.ReadKey(true).Key != ConsoleKey.OemPlus);
So this is what I thought to start with but I'm not sure if its the right way.
I managed to find the key available so I think that will check whether or not the user pressed the = key.
It needs to check for every char the user write but the all input in my opinion need to be string.
Anywhay thanks for helpers.
You will need something like this:
string s = "";
while(true)
{
char c = Console.ReadKey().KeyChar;
if(c == '=')
break;
s += c;
}
// here comes the part where you parse and evaluate the formula in s and print the result
try this concept
char x = Console.ReadKey().KeyChar;
if(x != '='){
sum = sum + num;
}else{
Console.WriteLine(sum);
}

Code won't give desired output or read second input

Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails

Setting random values from an Array into a List till condition is met. in C#

I want to set new random values from an Array into a List till one of two conditions is met. But it's only letting me add another 1 value without considering the condition. After I enter "y" the program letting me to get another value and then it asking me again if I want another card, when I enter "y" again , the code move on without letting me add another value.
The second problem is with the if(Hands.playerHand.Sum() > 22) I want the program to calculate the total value of the list and if it's more then 22 then execute the command.
Thank you!
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while(secondHand)
{
//if user want another card, this programm will ganerate another card and store it inside playerHand
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
if(Hands.playerHand.Sum() > 22)
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
So I changed the code a little. Now I can choose as many values as I want but I have a problem with the while (secondHandNo) and the while (Hands.playerHand.Sum() > 21) commands. When I enter "n" after taking another card the while (secondHandNo) which should continue the code wont executed. The while (Hands.playerHand.Sum() > 21) doesn't executed as well. It's just giving me more values no matter what my answer is. Note that when I enter "n" right away without taking another card, the command work just fine and it's taking me to the rest of the code.
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
}
while (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
You have quite a few issues here:
You are not storing the result from the console. This can be solve easily:
userAnotherCard = Console.ReadLine();
Even if we stored it, in the while your condition checks a value that was previously assigned and is never changed. This the reason that you are in an endless loop. I would replace it simply with the condition itself:
while (userAnotherCard == "y")
It seems you are using while break instead of a simple if:
if (Hands.playerHand.Sum() > 21)
while (secondHandNo) break; is useless and can be removed from the code.
That should be enough. Final code can look like this:
string userAnotherCard = Console.ReadLine();
while (userAnotherCard == "y")
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
userAnotherCard = Console.ReadLine();
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
}
Ok I was able to fix this block of code. It seems to work now. I set the whole block into while loop and set each condition with an if statement and a break; if condition is met.
while (true)
{
Console.WriteLine("Would u like to take another card?");
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
if (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
}
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
if (secondHandNo)
break;
}

C# stop user inputting a character/string instead of integer [duplicate]

This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 6 years ago.
I am asking users to input a int for their age but the program crashes when they input a string(obviously).
How would I go about allowing them to input a char/string but the program to display a funny message and then quit?.
This is what I have got so far:
Console.WriteLine("Please can you enter your age");
int userage = Convert.ToInt32(Console.ReadLine());
if (userage < 16)
{
var underage = new underage();
underage.text();
}
else if (userage>122)
{
Console.WriteLine("No one has ever reached this age and so you can't possibly be this old");
Console.WriteLine("Please enter a different age next time!");
Console.WriteLine("Unless you really are this old, in which case don't work!!");
Console.WriteLine("Press any key to exit the program.\n");
Environment.Exit(0);
}
else if(userage<122)
{
Console.WriteLine("Ah brilliant, you are old enough to use our services\n");
Console.WriteLine("We shall continue as first planned\n");
}
else
{
}
try:
Console.WriteLine("Please can you enter your age");
int userage;
if (int.TryParse(Console.ReadLine(), out userage))
{
//your if block
}
else
{
Console.WriteLine("Your input is funny and I am a funny message\n");
Environment.Exit(0);
}

Categories

Resources