【发布时间】:2021-07-10 06:38:07
【问题描述】:
我正在尝试制作密码验证器,但是当我输入数字时,此代码会抛出 IndexOutOfRangeException:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
string password = textBox1.Text;
if (password.All(c => Char.IsLetterOrDigit(c)))
{
button4.Text = "✓";
button4.ForeColor = System.Drawing.Color.Black;
button4.BackColor = System.Drawing.Color.Green;
if (password.Length >= 3 && password.Length <= 8)
{
button1.Text = "✓";
button1.ForeColor = System.Drawing.Color.Black;
button1.BackColor = System.Drawing.Color.Green;
if (password.Any(char.IsDigit))
{
button2.Text = "✓";
button2.ForeColor = System.Drawing.Color.Black;
button2.BackColor = System.Drawing.Color.Green;
// Error thrown below when I input a number
if (char.IsUpper(password[0]) && (char.IsLower(password[8])))
{
label1.Text = " Valid";
label1.ForeColor = System.Drawing.Color.Green;
button3.Text = "✓";
button3.ForeColor = System.Drawing.Color.Black;
button3.BackColor = System.Drawing.Color.Green;
}
else
{
label1.Text = " Invalid";
label1.ForeColor = System.Drawing.Color.DarkRed;
button2.Text = "✖";
button2.ForeColor = System.Drawing.Color.Black;
button2.BackColor = System.Drawing.Color.DarkRed;
}
}
else
{
label1.Text = " Invalid";
label1.ForeColor = System.Drawing.Color.DarkRed;
button3.Text = "✖";
button3.ForeColor = System.Drawing.Color.Black;
button3.BackColor = System.Drawing.Color.DarkRed;
}
}
else
{
label1.Text = " Invalid";
label1.ForeColor = System.Drawing.Color.DarkRed;
button1.Text = "✖";
button1.ForeColor = System.Drawing.Color.Black;
button1.BackColor = System.Drawing.Color.DarkRed;
}
}
else
{
button4.Text = "✖";
button4.ForeColor = System.Drawing.Color.Black;
button4.BackColor = System.Drawing.Color.DarkRed;
}
}
}
}
【问题讨论】:
-
你能分享更多关于你的代码的细节吗?你在哪里定义了
password变量?它来自哪里? -
您的输入字符串至少有 9 个字符长吗?否则,当您尝试访问
password[8]时,您会得到一个IndexOutOfRangeException -
你得到什么错误,哪一行抛出它?
-
@Rafalon 这是我得到的例外(密码必须是 3-8 个字母长)你能详细说明这个错误的含义吗,我不明白