samedi 24 octobre 2020

Collect int from user and add to array till they type "OK"

so... i need a help for my uni project. it asks to write a program that collects numbers from user and add them to array till they type ok and when they type okay show the sum of the array. this is what i came up with till now and it recives numbers just fine but when i type ok it showes error and says its string format. what should i do...? where have i gone wrong..?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace array_sum
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = new int[10];
            int i = -1;
   
            Console.WriteLine("please eneter as many numbers as you want and when your done type: OK");
            string input = Console.ReadLine();
            while (true && input!= "ok")
            {
                if (int.TryParse(input, out int numsum))
                {
                    nums[i + 1] = int.Parse(Console.ReadLine());
                    Array.Resize(ref nums, nums.Length + 1);
                    numsum = nums.Sum();
                }
                else  
                {
                    break;
                }
            }
                if (input == "ok")
                {
               int  numssums = nums.Sum ();
                    Console.WriteLine(numssums);
                }
                Console.ReadKey(); 
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire