C# 从 readline 问题将字符串转换为数组

我正在做一些 C# 练习,作业是检查 att 瑞典 SSN 是否颁发给女性或男性。

该算法检查第九个数字是否可被 0 整除,则为女性,否则为男性。

如果我在字符串变量中使用硬编码的“nr”,该算法会起作用,但如果我尝试从 readline 语句中读取它,则会收到以下错误:

指数超出范围。必须为非负数且小于集合的大小。参数名称:startIndex

这是我正在使用的代码:

//string personnr = "860215-2097";

string personnr = "";

char[] arr;

    

public void CheckGender(string pnr)

{

    arr = personnr.ToCharArray(9, 1);

    

    if (personnr[9] %2 == 0)

    {

        Console.WriteLine($"Woman!!!");

    }

    else

    {

        Console.WriteLine($"Man!!!");

    }

}

    

public void PrintPersonNr()

{

    Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");

    string nr = Console.ReadLine();

    CheckGender(nr);

}

所以PrintPersonNr我猜这是我的方法不能正常工作。


四季花海
浏览 126回答 3
3回答

白板的微信

你可以试试这个:public enum SSNGender{&nbsp; Female,&nbsp; Male}class Program{&nbsp; static public Dictionary<SSNGender, string> SSNGenderText&nbsp; &nbsp; = new Dictionary<SSNGender, string>()&nbsp; {&nbsp; &nbsp; { SSNGender.Female, "Woman" },&nbsp; &nbsp; { SSNGender.Male, "Man" },&nbsp; };&nbsp; static public SSNGender CheckSSNGender(string pnr)&nbsp; {&nbsp; &nbsp; // Here check the validity of the pnr (length, format...)&nbsp; &nbsp; return pnr[9] % 2 == 0 ? SSNGender.Female : SSNGender.Male;&nbsp; }&nbsp; static void Main(string[] args)&nbsp; {&nbsp; &nbsp; Console.WriteLine("Write a personnr in the format yymmdd-nnnn: ");&nbsp; &nbsp; string nr = Console.ReadLine();&nbsp; &nbsp; var result = CheckSSNGender(nr);&nbsp; &nbsp; Console.WriteLine(SSNGenderText[result]);&nbsp; &nbsp; Console.ReadKey();&nbsp; }

慕慕森

尝试以下操作:&nbsp; &nbsp; &nbsp; &nbsp; public void CheckGender(string pnr)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string arr = pnr.Substring(10, 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (arr == "0")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Woman!!!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Man!!!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

繁花不似锦

您需要做的是使用模运算符,然后检查该数字是否可以被二整除,如果结果为零,则它是偶数。还有一个基本问题,您需要检查字符是否是数字。如果是,则需要完成操作,如果不是,则需要让用户知道。public void CheckGender(string pnr){    string arr = pnr.Substring(9, 1);    int num =0;    if (int.TryParse(arr, num))    {        if ((num % 2) == "0")        {            Console.WriteLine("Man!!!");        }        else        {            Console.WriteLine("Woman!!!");        }    }    else    {        Console.WriteLine("Not a number!");    }}祝你运动顺利!
打开App,查看更多内容
随时随地看视频慕课网APP