简体   繁体   中英

Getting User Input and Adding it to an array at C#

I am trying to get input from user 5 times and add those values to marks array;

Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements" . After getting input from user how can I add them to marks array? Any tips would be helpful.

using System;

    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    class Program
    {
        static void Main()
        {
                double average =0;
                int [] marks = new int[] { };

                 for (int a = 0; a < 5; a++){
                    Console.WriteLine("Enter 5 elements:"); 
                string line = Console.ReadLine(); 
                 Console.WriteLine(line);

            }
                for (int i = 0; i < marks.Length; i++){
                    average = marks.Average();
            }
                if(average>0){
                    Console.WriteLine("Positive");
                }else{
                    Console.WriteLine("Negative");
                }           
        }
    }

I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).

static void Main()
{
    int[] marks = new int[5];

    int a = 0;

    Console.WriteLine("Enter 5 elements:");

    while (a < 5)
    {
        if (int.TryParse(Console.ReadLine(), out marks[a]))
            a++;
        else
            Console.WriteLine("You didn't enter a number! Please enter again!");
    }

    double average = marks.Average();

    if (average > 0)
        Console.WriteLine("Positive");
    else
        Console.WriteLine("Negative");
}

DEMO HERE

Edited my answer to illustrate solving your problem without a for loop.

class Program
{
    const int numberOfMarks = 5;
    static void Main()
    {
        List<int> marks = new List<int>();
        Enumerable.Range(1, numberOfMarks)
        .ForEach((i) => {
            Console.Write($"Enter element {i}:");
            marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
            Console.WriteLine($" {valueRead}");
        });
        Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
    }
}

Follow Stackoverflow Answer

since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For eg

string words = "83";

int number = int.Parse(words);

Edit: using string variable in parsing.

This will help you, just copy and paste it. There are some explanation with comments.

class Program
{
    static void Main()
    {
        const int numberOfMarks = 5;
        int[] marks = new int[numberOfMarks];

        Console.WriteLine("Enter 5 elements:");
        for (int a = 0; a < numberOfMarks; a++)
        {
            // If entered character not a number, give a chance to try again till number not entered
            while(!int.TryParse(Console.ReadLine(), out marks[a]))
            {
                Console.WriteLine("Entered not a character");
            }

            Console.WriteLine("You entered : " + marks[a]);
        }

        // Have to call Average only once.
        var avg = marks.Average();
        Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
        Console.ReadLine();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM