Почему содержимое моего массива печатается дважды в C #? - PullRequest
0 голосов
/ 03 октября 2018

Я не понимаю, почему этот код печатает содержимое массива дважды.

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, и я не понимаю, почему.Любая помощь будет оценена спасибо.

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

вы специально создаете «сначала», затем печатаете его в 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());
}
0 голосов
/ 03 октября 2018

Это потому, что у вас есть два цикла , сначала вы печатаете каждый символ в 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);
...