I am currently learning the C # language. I have the following task:
Write program that:
Reads an input of integer numbers and adds them to a stack
Reads commands until "end" is received
Prints the sum of the remaining elements of the stack
Input
- On the first line you will receive an array of integers
- On the next lines, until the "end" command is given, you will receive commands - a single command and one or two numbers after the command, depending on what command you are given
- If the command is "add", you will always receive exactly two numbers after the command which you need to add in the stack
- If the command is "remove", you will always receive exactly one number after the command which represents the count of the numbers you need to remove from the stack. If there are not enough elements skip the command. Output
- When the "end" command is received, you need to Print the sum of the remaining elements in the stack
Input
1 2 3 4
adD 5 6
REmove 3
eNd
Output
Sum: 6
input:
3 5 8 4 1 9
add 19 32
remove 10
add 89 22
remove 4
remove 3
end
Output:
Sum: 16
I wrote this code. From the beginning it works, I enter a number of numbers and put them in the stack without any problems. From now on, after entering what I want to do "add", "remove" or "end", an error appears after adding numbers. after I decide to add an element the program allows me to enter numbers indefinitely until I try to change the addition of numbers with one of the other two options I get this error: System.FormatException: 'Input string was not in a correct format.'
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Stack_Sum
{
class Program
{
static void Main(string[] args)
{
Stack<int> numbers = new Stack<int>();
string input = Console.ReadLine();
string[] number = Regex.Split(input, @"\D+");
foreach (string value in number)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
numbers.Push(i);
}
}
string option = Console.ReadLine();
while (true)
{
switch (option.ToLower())
{
case "add":
int addToStack = Int32.Parse(Console.ReadLine());
for (int i = 0; i < 2; i++)
{
numbers.Push(addToStack);
}
continue;
case "remove":
int popItem = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < popItem; i++)
{
numbers.Pop();
}
continue;
case "end":
foreach (var Stack_Sum in numbers)
{
int sum = 0;
sum += Stack_Sum;
}
break;
}
}
}
}
}