+ 2

Can someone explain how I can use ReadLine to create a Yes or No answer with different if or else if responces in the WriteLine

Can someone explain how I can turn a Read.Line into a yes or no answer. I tried to use bool varibles and used the Convert.ToBoolen. but I can't get it to work even when my syntax seems fine. the answer true and false work, but bool happy; Console.Write("Are you happy?"); happy=Convert.ToBoolen(Console.ReadLine()); bool yes = true; bool no = false; if (happy == yes) { Console.WriteLine("You are happy");} else if (happy == no) {Console.WriteLine("You are sad");} else {Console.WriteLine("yes or no only");} .

7th Feb 2017, 6:57 PM
Steven Bennett
Steven Bennett - avatar
3 Réponses
+ 2
to read a line use: string answer = Console.ReadLine(); To test for Yes use: if (answer == "yes") the same with "no". To make it more robust use: if (answer.Trim().ToLower() == "yes") Trim removes spaces from start and end of string, ToLower makes string lowercase, so even if you enter " Yes" it will still work. Try something like this. ............ Console.WriteLine("Are you happy (Yes/No)?"); string answer = Console.ReadLine().Trim().ToLower(); if (answer == "yes") { Console.WriteLine("Happy"); } else if (answer == "no") { Console.WriteLine("Sad"); } else { Console.WriteLine("Yes/No please."); } ............. And for future, "bool yes = true" and then testing if (happy == yes) is redundant. Shorter way: if (happy) { Console.WriteLine("I'm happy"); } else ... or you could test like this: if (!happy) { Console.WriteLine("I'm not happy"); } else ...
7th Feb 2017, 8:52 PM
Ugnius Soraka
+ 2
@Ugnius Soraka. Thank you very much. Totally solved my issue. And thank you for the Trim and Lower. Awesome.
7th Feb 2017, 10:15 PM
Steven Bennett
Steven Bennett - avatar
+ 1
I tried the char keyword and it didn't work for me. I was able to use the switch conditional like char using 1 for yes and 2 for no. Console.WriteLine("Are you happy, 1 for yes, 2 for no"); int happy = Convert.ToInt32(Console.Readline()); switch (happy) { case 1: Console.WriteLine("Happy"); break; case 2: Console.WriteLine("Sad"); break; default: Console.WriteLine("1 for yes or 2 for no only); break;
7th Feb 2017, 9:44 PM
Steven Bennett
Steven Bennett - avatar