这是我的代码:
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 ();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道为什么程序会退出,即使我输入"男孩"或"女孩"以及如何解决这个问题.
简单逻辑:
Sex != "boy" || Sex != "girl"
Run Code Online (Sandbox Code Playgroud)
永远都是真的.
你需要使用
Sex != "boy" && Sex != "girl"
Run Code Online (Sandbox Code Playgroud)
代替.
一些额外的说明:
==和!=字符串就好了.Environment.Exit,只是return.如果需要返回错误代码,请将签名更改Main为int Main()和return 1;.但请注意,在Windows上,应用程序可能会认为返回非成功代码的应用程序以某种方式失败并报告它 - 例如,Total Commander将弹出一条消息.\n.使用Environment.NewLine,或只是坚持Console.WriteLine使用终结.string.Format拼接复杂的字符串:string.Format("Your name is {0} and your age is {1}.", Name, Age). If you're on C# 6+, string interpolation is even nicer:$("你的名字是{Name},你的年龄是{Age}.")`.Sex.Equals("boy", StringComparison.CurrentCultureIgnoreCase).您需要将 if 语句从“OR”更改为“AND”:
if (!Sex.Equals ("boy") || !Sex.Equals ("girl"))
Run Code Online (Sandbox Code Playgroud)
如果满足其中一个条件,“OR”语句的计算结果为 true。因此,如果您输入“boy”,则第二条语句!Sex.Equals("girl")为 true,因此它会执行 if 语句中的代码。
相反,请使用“AND”语句,仅当两个参数都为 true 时,该语句的计算结果才为 true。
if (!Sex.Equals ("boy") && !Sex.Equals ("girl"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6462 次 |
| 最近记录: |