c# - 这个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# 中没有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;
}
}
推荐阅读
- javascript - 文档满足条件时未调用 Firestore onRemove
- r - 如何从 apply() 函数输出中获取行名?
- javascript - Javascript - 如何打破循环动画帧?
- python - 编辑现有 XML 文件并通过 Jboss 发送帖子
- javascript - Next/Apollo:如果在 getInitialProps 中运行了相关查询,如何正确更新 apollo 缓存
- c++ - 相互依赖的类中的 C++ 函数指针
- java - Visual Studio 无法正确运行我的代码
- python - TypeError:处理图像时不能将序列乘以“浮点”类型的非整数
- javascript - 用于提取国家名称的正则表达式
- sql - 如何使用我的数据库中的所有表名创建一个表,并为每个表创建表中的列数