1

I've developed a new found interest in programming however I have had some problems. I have tried to make a simple program in which a user enters 10 numbers, if the number is 0 it will stop, then adds those numbers to a list then prints the list at the end. However, my program only asks for 4 numbers before stopping, it doesn't stop when 0 is entered and the "Enter a number message" at the start prints 3 times each time it goes round the loop.

Any help would be appreciated

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args) {
            // I want to make a list
            // keep asking the user for values
            // which will then add those values onto the list
            // then print the list
            // create a list
            List<int> list = new List<int>();
            int count = 0;

            while (count < 10) {
                Console.WriteLine("Enter a value to add to the list");
                int number = Console.Read();
                list.Add(number);

                if (number == 0) {
                    break;
                }

                count++;
            }

            Console.WriteLine("The final list looks like this");

            foreach (int number in list) {
                Console.WriteLine(number);
                Console.ReadLine();
            }
        }
    }
}
4
  • Hi, I just edited your code to match indents and brackets. I suggest you make this a rule of thumb as this will often make it easier for you to find the problem. Commented Jan 5, 2014 at 12:13
  • Advice: rather than doing a while and handling the count yourself, here, you could simplify your life using for(int count=0 ; count < 10 ; count++) Commented Jan 5, 2014 at 12:15
  • Make yourself familiar with the debugger. Debugging is by far easier than staring at the code and reasoning about it. Commented Jan 5, 2014 at 12:21
  • Thank you both very much, massive help I am grateful! Commented Jan 5, 2014 at 12:22

1 Answer 1

3

The problem is with Console.Read() - It reads a byte rather than a string that should be converted into int in your case.

What you're looking for is Console.ReadLine(), surrounded with int.Parse(). Something like this:

int number = int.Parse(Console.ReadLine());
Sign up to request clarification or add additional context in comments.

1 Comment

Although this may result in an exception if the user didn't input a valid number. You should always make sure that it's a number by int.TryParse() first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.