我不明白为什么这段代码两次打印数组的内容。
static void Main(string[] args)
{
Int64 userlength;
Int64 userlengthcounter;
String unencrypted;
char current;
start:
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
goto start;
}
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}
Console.ReadLine();
}
例如,输入abcd将返回abcdabcd,我不明白为什么。任何帮助将不胜感激。
答案 0 :(得分:2)
这是因为您有两个 循环,首先需要在unencrypted
循环中的for
中打印每个字符,并将字符存储在first
数组中。
然后,您遍历数组并使用foreach
重新打印字符。
其他说明:使用goto
几乎总是 是个坏主意,因为它会使您的代码难以理解且难以理解。因为您必须手动跟踪代码跳转的位置。
您可以使用do-while
循环来做同样的事情。
do {
Console.WriteLine("Please enter how many characters the string you want encrypyted to be:");
userlength = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Please enter the string you want to be encrypted:");
unencrypted = Console.ReadLine();
int[] first = new int[userlength];
int[] second = new int[userlength];
if (userlength != unencrypted.Length)
{
Console.WriteLine("The string you entered was not the same length as the number of characters you specified");
}
} while(userlength != unencrypted.Length);
答案 1 :(得分:0)
您专门构建“ first”,然后将其打印在foreach中,基本上两次显示相同的内容:
for (int i = 0; i < userlength; i++)
{
Console.WriteLine(unencrypted[i]);
current = unencrypted[i];
first[i] = current;
}
foreach (char item in first)
{
Console.WriteLine(item.ToString());
}