-1

My goal with this code is to store user-inputted price data in a do-while loop so that I can put it through calculations for the shipping address. I decided to go at an approach that allows the array to increase in size with each piece of data inputted. The array does increase in size, but the inputted data gets deleted with every loop. Plus, I have to use a do-while loop

        {
            int itemList = 0;
            string userAnswer;

            //This section of the code is to have the user input their data for the later calculations
            //The do-while loop is used to count how many items the user has inputted, as well as storing the prices for the later calculations
            Console.WriteLine("Enter the price of your item:");
            do
            {
                itemList++;
                double[] List = new double[itemList];
                for (int i = 0; i < itemList; i++)
                {
                    List[i] = Convert.ToDouble(Console.ReadLine());
                }
                for (int i = 0; i < itemList; i++)
                {
                    Console.Write(List[i] + " ");
                }
                Console.WriteLine("Do you wish to enter more item prices? Yes or No");
                userAnswer = Console.ReadLine();

                if (userAnswer == "No")
                {
                    break;
                }

            }
            while (userAnswer == "Yes");```
  • 1
    `double[] List = new double[itemList];` Creates a new list each time. [How to extend arrays in C#](https://stackoverflow.com/a/27230762) – 001 Nov 06 '20 at 19:48
  • You are creating a new array each iteration. You need to _resize_ the existing array, if you want to do it that way. See duplicate. Better still, use a `List`, allocated _once_ before the loop. Also see duplicate. – Peter Duniho Nov 06 '20 at 21:13

1 Answers1

0

Use a List instead of an array and set it outside of the do-while loop. To add a value to the list, use its Add method. Also, don't print its contents until after the do-while loop.

Paramecium13
  • 345
  • 1
  • 7