How to check user input with if command - c#

Not sure if I'm overlooking something really simple but I'm trying to make a program that allows a user to enter 1 of 2 letters and then run code based on the input. Seems simple enough but I've run into several errors with all the ways I thought this could work. Here is the code:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys = ConsoleKey.Y)
Console.Clear();
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
I added in the else portion (unfinished)just to get an idea if If i'm going the right direction with the intended goal as well. Would I be able to make an else statement that triggers if neither Y or N is pressed this way?

Well, first of all, you are making an assignment, not comparing:
if (ansys.Key = ConsoleKey.Y)
is wrong, use:
if (ansys.Key == ConsoleKey.X)
== is comparison, = is assignment. Don't confuse them, it may cause serious problems.
For you question, if you simply add an else if statement checking for "No" answer, then else statement won't be triggered if Y or N is pressed. If at least if statement is executed, else statement won't be executed.
Your code should look like:
if (ansys == ConsoleKey.Y) {
// code if yes
}
else if (ansys == ConsoleKey.N) {
// code if no
}
else {
// code if neither
}
Edit:
Since my primary language is not C#, I looked at documentation to check my answer. I figured out that if you use ReadKey() it does not return a ConsoleKey, it returns struct ConsoleKeyInfo. You need to use Key member of the ConsoleKeyInfo to access the pressed key. Please re-check the code.

Try this approach:
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Y)
{
Console.Clear();
}
else if (cki.Key == Console.N)
{
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
You can find th examples here: ReadKey - examples

Try this:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
var ansys = Console.ReadKey();
if (ansys.KeyChar == 'y' || ansys.KeyChar == 'Y')
{
//Handle yes case
}
if (ansys.KeyChar == 'n' || ansys.KeyChar == 'N')
{
//Handle no case
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}

Try this (couldnt test it)
This will ask for the name until the confirmation answer is Y
If the input when asked Y or N is another thing, it will ask again for the name confirmation.
string name = "";
while (name.equals(""))
{
name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
String answer = "";
while(answer.equals(""))
{
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys == ConsoleKey.Y || ansys == ConsoleKey.N)
{
answer = ansys.ToString();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only!!");
}
}
if(!answer.equals("Y"))
name = "";
}
Im not sure if ansys.ToString() is a valid method, and if that returns the "Y" string in case the key pressed was Y

Related

C# “String may be null here” but I don't think it can be null

So I wanted to make a sort of “name checker” that’s always had the first letter be capital and the rest lowercase. I got that to work but whenever I got past the name checker and wanted to use the name in future code, it would always say “string may be null here.” I have tried many things like adding a ? But nothing works. I don’t think it can be null but maybe I’m wrong. Here is my code here:
class Program
{
static void Main()
{
string? name, choice;
bool finishnameingcharacter;
finishnamingcharacter = true;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if(name != null)
{
name = char.ToUpper(name[0]) + name.Substring(1);
}
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = 1;
}
if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
The "name" at the bottom is where the error is. If there's any confusion about my question ask me. I tried my best to explain it.
I could not compile your code, so I made some changes
static void Main()
{
var name = string.Empty;
var choice = string.Empty;
do
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if (name != null && name.Length>1)
name = char.ToUpper(name[0]) + name.Substring(1);
Console.WriteLine("");
Console.WriteLine("Your name is " + name + ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if (choice == "1") break;
if (choice == "2")Console.WriteLine("");
else Console.WriteLine("Invalid Claim");
} while (true);
Console.WriteLine(name);
}
Why use a nullable string in this software?
You didn't initialize the name at the beginning, if your loop will never run, then the name output line will be NULL. This is what your error points to.
It is better to initialize variables before their first use, as they can be NULL by default (valid for reference types such as classes). For a string, one option would be String.Empty
string name = String.Empty, choice = String.Empty;
These two lines can be combined:
bool finishnameingcharacter;
finishnamingcharacter = true;
// Replaced by
bool finishnameingcharacter = true;
On the next line in the while loop, you check the condition: finishingnamingcharacter == false. The loop checks the condition and only then executes. To execute the loop, you need the condition to be TRUE, but it will not take this value, because earlier you defined the variable finishnamingcharacter = true. true != false. By default you need to define this variable as false
bool finishnameingcharacter = false;
The user can enter an empty string value, so converting it to lowercase immediately doesn't matter, as long as it checks for an empty string. There is a special method for checking if a string is empty: string.IsNullOrEmpty() - it returns true if the string is empty or null.
If the user entered the wrong name, then we need to ask him to enter again, for this, the continue operator is used.
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
For boolean values it is better to use reserved words, i.e. instead of finishnamingcharacter = 1 it is better to write finishnamingcharacter = true
Rest of the code looks good. We all took the first steps :)
Full modified code here:
class Program
{
static void Main()
{
string name = String.Empty choice = String.Empty;
bool finishnameingcharacter = false;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = true;
}
else if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
PS There is a special method TextInfo.ToTitleCase() "wAr aNd pEaCe to titlecase: War And Peace" - I advise you to read

implementing a play again feature in a random number guess generator

I have been doing some programming exercises in university lately and i came across one that wanted the user to guess between the numbers 1 and 100. They also want it to have the ability to let the user play again. When first ran the program is fine but when i say 'y' to play again it generates the same number i previously guessed:
I found some solutions however there was so much spaghetti code i couldn't read it on websites. is there any way to save a few lines of code.
here is my source:
int guess = 0;
Random r1 = new Random();
int answer = r1.Next(1, 100);
bool finished = false;
while (!finished)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
}//end of nested else
}//end of while
The reason why the same number is being given every time to guess is that you do not generate it if the user wants to continue the game, but instead you use what was already declared.
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
string playAgain = null;
playAgain = Console.ReadLine();
if (playAgain == "n")
{
finished = true;
}
answer = r1.Next(1,100);
}//end of nested else
If you want to get rid of some lines, then you can simply declare some variable inside of the loop.
Random r1 = new Random();
int answer = r1.Next(1, 100);
while (true)
{
Console.WriteLine("please guess a number between 1 - 100");
guess = int.Parse(Console.ReadLine());
if (guess < answer)
{
Console.WriteLine("your answer is too low please try again!");
}
else if (guess > answer)
{
Console.WriteLine("your answer is too high please try again!");
}
else if (guess == answer)//nested
{
Console.WriteLine("your answer is correct!");
Console.WriteLine("answer:" + answer);
Console.WriteLine("Play again? ('y' or 'n')");
if (Console.ReadLine() == "n")
{
break; // stop the loop
}
}//end of nested else
}//end of while
Because before restarting the guess, the field "answer" is always the previously generated random value "54". Therefore, if the user enters "y", you can add a statement to reset the value of "answer".
// code omitted
// ...
// reset answer
if(playAgain == "y")
{
answer = r1.Next(1, 100);
}
if (playAgain == "n")
{
finished = true;
}

Is it possible to skip the next line if 'x' text is entered? C#

I apologize if this has already been answered else where, I've looked but couldn't find anything. Also this is my first time ever asking a programming related question, I'm really bad with articulating. I'm working on it. Thank you in advanced!
Is it possible to skip the next lines asking for input, to the if statement if input is exit?
while (isAdding == true)
{
Console.Write("First Name: ");
input = Console.ReadLine();
Console.Write("Last Name: ");
input2 = Console.ReadLine();
Console.Write("Address: ");
input3 = Console.ReadLine();
Console.Write("Phone Number: ");
input4 = Console.ReadLine();
Console.Write("Email Address: ");
input5 = Console.ReadLine();
if (input == "exit" || input2 == "exit" || input3 == "exit" || input4 == "exit" || input5 == "exit")
{
isAdding = false;
//break;
}
With your current syntax, you need to check for the input values on every step.
Console.Write("First Name: ");
input = Console.ReadLine();
if(input == "exit"){
break;
}
Console.Write("Last Name: ");
input2 = Console.ReadLine();
if(input2 == "exit"){
break;
}
If you're purpose is to stop the iteration after all the inputs are saved, then your code is sufficient.
A cleaner way is putting the evaluation inside a function.
public bool ShouldExit(string firstName, string lastName){
if(firstName == "exit" || lastName == "exit"){
return true
}
}
Then call that function instead.
if (ShouldExit(input,input2))
{
isAdding = false;
//break;
}

Add a second command that calls another method?

I'm remaking a text-based adventure game. During the character creation, I'd like for the user, at any time, to type 'skillset' and list all the traits that a specific race has. I've tried for a couple hours and can't seem to figure it out.
This is my character creation class.
public string userCommand_SeachSkill;
SkillSet searchSkill = new SkillSet();
public void Create_Character()
{
// CHOOSE GENDER //
do
{
validate = 0;
Console.Clear();
Console.Write("Are you male or female? (f/m): ");
Sex = Console.ReadLine().ToUpper();
if (Sex == "M" || Sex == "F")
{
validate = 1;
}
else if (Sex != "M" || Sex != "F")
{
Console.WriteLine("You must enter 'm' or 'f'");
}
} while (validate == 0);
And this is my Skill Set Class. Everything in the if/else statements are methods to print the traits of a race to the console. Let me know if there is anything else I can add to better ask my question. Thank you in advance! :)
ClassAttributes classes = new ClassAttributes();
Character character = new Character();
skillset = Console.ReadLine().ToUpper();
do
{
validate = 0;
if (skillset == "HUMAN")
{
classes.SkillSetHuman();
}
else if (skillset == "ORC")
{
classes.SkillSetOrc();
}
else if (skillset == "ELF")
{
classes.SkillSetElf();
}
else if (skillset == "EXIT")
{
validate = 1;
character.Create_Character();
}
} while (validate == 0);
I think you're looking for something like an event. C# Console Applications only seem to have one kind of event, it fires when ctrl+c or ctrl+break happens. You could handle your skillset input/output logic in the function handler
You can read more here:
https://msdn.microsoft.com/library/system.console.cancelkeypress(v=vs.110).aspx
If you really need the word to be typed, you could capture everything that is typed in a special function, instead of using regular Console.ReadLine(). Something like this:
public static string CustomReadLine()
{
ConsoleKeyInfo cki;
string capturedInput = "";
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
break;
else if (cki.Key == ConsoleKey.Spacebar)
{
capturedInput += " ";
Console.Write(" ");
}
else if (cki.Key == ConsoleKey.Backspace)
{
capturedInput = capturedInput.Remove(capturedInput.Length - 1);
Console.Clear();
Console.Write(capturedInput);
}
else
{
capturedInput += cki.KeyChar;
Console.Write(cki.KeyChar);
}
if (capturedInput.ToUpper().Contains("SKILLSET"))
{
capturedInput = "";
skillsetTyped();
return "";
}
}
return capturedInput;
}
then inside your Create_Character, do
...
do
{
Console.Write("Are you male or female? (f/m): ");
Sex = CustomReadLine();
} while (String.IsNullOrEmpty(sex));
And finally, handle the skillset logic here
protected static void skillsetTyped()
{
Console.Write("\nWrite your skillset capture/display logic here\n");
}
This is just a draft and has some minor bugs, but I believe it's close to what you really want.

Saving values within if statement C#

I'm a newbie at C# and I'm having some difficulties writing a program that is going to let you save values in a variable, everything is working fine, except I can't save values into my variable. Here's the code:
while (true)
{
//Menu
Console.WriteLine (" \n\tWelcome!");
Console.WriteLine (" \t[1]Store value");
Console.WriteLine (" \t[2]Write message");
Console.WriteLine (" \t[3]Clear the console");
Console.WriteLine (" \t[4]Shut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32 (Console.ReadLine ());
//Users message
string usrMsg = null;
//if statement
if (choice == 1) {
usrMsg += Console.ReadLine ();
} else if (choice == 2) {
Console.WriteLine (usrMsg);
} else if (choice == 3) {
//Shuts down program
break;
} else if (choice == 4) {
//Clear program
Console.Clear ();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
You just move the usrMsg variable out of while block as a global the value will be saved.
//Users message
string usrMsg = null;
while (true)
{
//Menu
Console.WriteLine(" \n\tWelcome!");
Console.WriteLine(" \t[1]Store value");
Console.WriteLine(" \t[2]Write message");
Console.WriteLine(" \t[3]Clear the console");
Console.WriteLine(" \t[4SShut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32(Console.ReadLine());
//if statement
if (choice == 1)
{
usrMsg += Console.ReadLine();
}
else if (choice == 2)
{
Console.WriteLine(usrMsg);
}
else if (choice == 3)
{
//Shuts down program
break;
}
else if (choice == 4)
{
//Clear program
Console.Clear();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
When this runs it always creates userMsg as null. That means that at best it will 'save' only 1 value when the user chooses '1'. However, this will never get displayed if the user selects '2' as when the user gets to the menu again userMsg will have been set to null again.
My assumption is that you're trying to save the number of times someone has selected '1' and then display that if the user then hits option '2'.
Stick this:
//Users message
string usrMsg = null;
outside of the 'while' loop.

Categories

Resources