[英]Why If statements using logical conditional operators && and != are giving me the wrong result?
我是編程新手,正在學習C#。 我正在開發一個程序,該程序可以加密和解密在文本框中輸入的文本。
我想確保當用戶單擊按鈕來加密或解密文本時,文本和密碼文本框不為空。 因此,在運行加密文本的代碼之前,我正在使用邏輯條件運算符&&
和!=
評估文本框。 當我將文本框的text屬性的值與一個空字符串進行比較時,似乎得到了錯誤的結果。
當我單擊文本框中沒有任何數據的加密或解密按鈕時,語句: if (text != " " && encryptPassword != " ")
行為就像每個測試都是正確的一樣,並且無論如何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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.