我刚开始用 C# 编程。我正在尝试构建一个简单的 Vigenere 文本加密工具作为个人项目。
我的问题应该很容易解决,但发现错误确实让我很紧张。在我的代码中,我试图做一个简单的检查,看看我的字符串中的字符是否是空格;我已经正确设置了我的 if 语句,但它正在跳过第一个测试并移动到 else if,即使第一个测试为真。我真的很喜欢这方面的一些帮助。
我的问题区域在底部。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class fun2013
{
public static void Main()
{
Console.WriteLine("fun 2013");
string UserName;
do
{
Console.Write("LOGIN//: ");
UserName = Console.ReadLine();
}
while(UserName != "Max");
Console.WriteLine(("Hello ") + (UserName) + (", enter your key below."));
//USER ENTERS TEXT AT THIS POINT
string loweredPass = Console.ReadLine().ToLower();
Console.WriteLine("Changing CASE...");
Console.WriteLine(loweredPass);
string Strippedpass = loweredPass.Replace(" ","");
Console.WriteLine("STRIPPING SPACES...");
Console.WriteLine(Strippedpass);
int passLength = Strippedpass.Length;
Console.WriteLine("Enter your message below.");
string userMessage = Console.ReadLine();
int MessageLength = userMessage.Length;
//BEGIN PROCESSING STRINGS INTO ARRAYS
string temp = "";
StringBuilder bcon = new StringBuilder();
char [] passArray = Strippedpass.ToCharArray();
char [] messArray = userMessage.ToCharArray();
string letterf = "";
for(int i=0, j=0; j < (MessageLength); i++, j++) //i used for key array, j used for message length
{
>>> if (messArray[i].ToString() == " ")
{
letterf = " ";
}
else if (messArray[i].ToString() != " ")
{
letterf = passArray[i].ToString();
}
if (i >= (passLength-1)) //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
{i = -1;} //-1 is used so it will go back to value of 0 on next loop
temp = letterf;
bcon.Append(temp);
}
Console.WriteLine();
Console.WriteLine(bcon);
Console.WriteLine("Press ENTER to continue...");
Console.ReadLine(); //KILL APPLICATION
}
}
感谢大家的帮助,但经过进一步检查,我发现我的 for 循环出错了。我正在使用与键数组(int i)相同的间隔来重置消息数组阅读器。我将其更改为使用正确的整数“j”。我还将“temp”字符串更新程序和字符串生成器放入循环中的每个 if 语句中。它现在运行正常。
for (int i=0, j=0; j < (MessageLength); i++, j++) //i used for key array, j used for message length
{
if (messArray[j].ToString() != " ")
{
letterf = passArray[i].ToString();
temp = letterf;
bcon.Append(temp);
}
else if (messArray[j].ToString() == " ")
{
letterf = " ";
temp = letterf;
bcon.Append(temp);
}
if (i >= (passLength-1)) //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
{i = -1;} //-1 is used so it will go back to value of 0 on next loop
}