为什么If语句使用逻辑条件运算符&&和!=给了我错误的结果
本文关键字:错误 结果 语句 为什么 条件运算符 If | 更新日期: 2023-09-27 18:12:35
我是编程新手,我正在学习c#。我正在编写一个程序,可以加密和解密文本框中输入的文本。
我想确保当用户单击按钮加密或解密文本时,文本和密码文本框不是空的。因此,我使用逻辑条件运算符&&
和!=
来评估文本框之前的代码加密文本运行。当我比较文本框的文本属性值与空字符串时,我似乎得到了错误的结果。
当我单击加密或解密按钮时,文本框中没有任何数据,语句:if (text != " " && encryptPassword != " ")
的行为就好像每个测试都是真的,并且无论如何都运行加密或解密代码。我试过使用equals
,玩括号,并扭转顺序无效。请帮助。
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 CryptoMakerII
{
public partial class CryptoMakerII : Form
{
public CryptoMakerII()
{
InitializeComponent();
}
private void UpdateControls(string crypto)
{
if (crypto == "Encrypt")
{
lblEncryptPassword.Visible = false;
txtEncryptPassword.Visible = false;
btnEncrypt.Visible = false;
txtDecryptPassword.Visible = true;
btnDecrypt.Visible = true;
lblDecryptPassword.Visible = true;
lblText.Text = "Encrypted Text";
//txtDecryptPassword.Text = " ";
//txtEncryptPassword.Text = " ";
}
else
{
lblEncryptPassword.Visible = true;
txtEncryptPassword.Visible = true;
btnEncrypt.Visible = true;
txtDecryptPassword.Visible = false;
btnDecrypt.Visible = false;
lblDecryptPassword.Visible = false;
lblText.Text = "Text to Encrypt";
txtDecryptPassword.Text = " ";
txtEncryptPassword.Text = " ";
}
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
DES_Crypto desCrypto = new DES_Crypto();
string text = txtText.Text;
string encryptPassword = txtEncryptPassword.Text;
if (text != " " && encryptPassword != " ")
{
string encryptedText = desCrypto.EncryptString(text, encryptPassword);
txtText.Text = encryptedText;
UpdateControls("Encrypt");
}
else
{
MessageBox.Show("Please enter text to encrypt and password");
}
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
DES_Crypto desCrypto = new DES_Crypto();
if (txtText.Text != " " && txtDecryptPassword.Text != " ")
if (txtDecryptPassword.Text == txtEncryptPassword.Text)
{
string decryptedText = desCrypto.DecryptString(txtText.Text, txtDecryptPassword.Text);
txtText.Text = decryptedText;
UpdateControls("Decrypt");
}
else
{
MessageBox.Show("The password is incorrect!");
}
else
MessageBox.Show("Please enter password to decrypt");
}
}
}
您正在检查字符串是否恰好等于1个空白字符,而不是检查它是否为空。c#有一个内置的方法来检查字符串是否为空:
string.IsNullOrEmpty(str)
所以不用
if (txtText.Text != " " && txtDecryptPassword.Text != " ")
试
if (!string.IsNullOrEmpty(txtText.Text) && !string.IsNullOrEmpty(txtDecryptPassword.Text))