首页 > 解决方案 > 这个c#验证密码的程序出错了?

问题描述

这是练习的广告:

ATM 机允许4位或6 位PIN 码,而PIN 码只能包含4位或6 位。

如果函数传递了一个有效的 PIN 字符串,则返回 true,否则返回 false。

例如:

ValidatePin("1234") => true

ValidatePin("12345") => false

ValidatePin("a234") => false

这是有错误的代码:

using System;
using System.Text.RegularExpressions;

public class Kata
{
    public static bool ValidatePin(string pin)
    {
        int pinn; //int called pinn declared
        int cont=0; // the same that the count
        int i;  //and the variable i for identify the for
        for(i=0;i<9999;i++)
        {
            cont +=1;
        }
        Console.WriteLine("Please enter the PIN:"); //tell the user to type the PIN number
        Console.ReadLine(pinn); //read the num pinn
        if(pinn>cont) //if
        {
            Console.WriteLine("Wrong output for",pinn);
        }

        return true || false;
}

错误:

时间:1889 毫秒 退出代码:1 测试结果:日志 src/Solution.cs(16,13):错误 CS1501:方法“ReadLine”没有重载需要 1 个参数 src/Solution.cs(16,22):错误 CS0165:使用未分配的局部变量“pinn”

标签: c#

解决方案


正如错误所说,在 C# 中没有Console.ReadLine()接受一个参数的重载方法,控制台类中的 ReadLine 方法从用户读取输入并将其存储在字符串变量中。

由于您的pinn变量是 type int,您需要将输入从转换Console.ReadLine()int喜欢,

pinn = Convert.ToInt32(Console.ReadLine());

现在您为变量分配了一些值pinn,因此您不会遇到第二个错误。


您可以在程序中进行很多改进,您的目标是检查引脚的长度是否为 4 或 6。true如果长度为 4 或 6,则返回,否则false

public class Kata
{
    public static bool ValidatePin(string pin)
    {

       //below condition will return true if length is 4 or 6, otherwise false
       var condition = !string.IsNullOrEmpty(pin)    //Null check for pin
                          && (pin.Length == 4 || pin.Length == 6)  //Length should be 4 or 6
                          && pin.All(char.IsDigit); // Check for all digits

       return condition;
    }
}

.NET 小提琴


推荐阅读