Here is my code:
using System;
namespace FirstProgram
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine ("What is your first name?");
String Name = Console.ReadLine ();
Console.WriteLine ("\nHi " + Name + "! Now tell me are you a boy or girl?");
String Sex = Console.ReadLine ();
if (!Sex.Equals ("boy") || !Sex.Equals ("girl")) {
Console.WriteLine ("\nERROR: You were supposed to type 'boy' or 'girl'\nPress any key to exit...");
Console.ReadKey ();
System.Environment.Exit (1);
}
Console.WriteLine ("\nOk so your name is " + Name + " and your are a " + Sex + "... Please tell me your age :)");
int Age = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("\nYou are " + Age + " years old!");
Console.ReadKey ();
}
}
}
I just want to know why the program exits even though I type "boy" or "girl" and how I can fix this.
Simple logic:
Sex != "boy" || Sex != "girl"
will always be true.
You need to use
Sex != "boy" && Sex != "girl"
instead.
A few extra notes:
== and != for strings just fine.Environment.Exit, just return. If you need to return an error code, change the signature of Main to int Main() and return 1;. But note that on Windows, applications may assume that an application that returned a non-success code failed in some way and report it - e.g. Total Commander will pop up a message.\n. Either use Environment.NewLine, or just stick to Console.WriteLine for endlines.string.Format for slapping together complex strings: string.Format("Your name is {0} and your age is {1}.", Name, Age). If you're on C# 6+, string interpolation is even nicer:$("Your name is {Name} and your age is {Age}.")`.Sex.Equals("boy", StringComparison.CurrentCultureIgnoreCase).You need to change your if statement from an "OR" to an "AND":
if (!Sex.Equals ("boy") || !Sex.Equals ("girl"))
An "OR" statement evaluates to true if one of the conditions is filled. So if you enter "boy", then the second statement, !Sex.Equals("girl") is true, therefore it executes the code within the if statement.
Instead, use an "AND" statement, which evaluates to true only if both arguments are true.
if (!Sex.Equals ("boy") && !Sex.Equals ("girl"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With