-3

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;
                }              
            }
        }
    }
}
  • *"...an error appears after adding numbers."* - please provide information on the error. Also, I strongly recommend you review https://stackoverflow.com/help/how-to-ask Thank you! – CoolBots Sep 20 '20 at 00:48
  • 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.' – ilian Dimitrov Sep 20 '20 at 00:54
  • 1
    First off your code expects the numbers on a separate line from the command. Second you read one integer after the add and then add the same integer to the stack twice instead of adding two different numbers. Also you're not checking if the remove is removing more numbers than are in the stack which you're suppose to skip if that's the case. – juharr Sep 20 '20 at 01:31
  • 1
    For future reference, don't do a code dump. Write a [mcve] that reliably reproduces _the one problem_ you are asking about. You can resolve the error you are seeing by either using a different method to parse the string (i.e. `TryParse()`, which will allow you to react to bad input however you see fit), or by not entering bad input in the first place. You undoubtedly are going to run into other problems with this code. This is a great opportunity for you to learn to use the built-in debugger in Visual Studio (or whatever IDE you're using). Only post questions which meet SO standards. – Peter Duniho Sep 20 '20 at 01:44
  • @PeterDuniho Quick question on this case - I don't think the OP understands *why* the duplicate question is applicable, based on their question (and certainly didn't at the time of posting) - is that still a "Close as Duplicate" situation? – CoolBots Sep 20 '20 at 01:49
  • 1
    @CoolBots: it is entirely possible that they don't understand, you are right. But that doesn't change the fact that the only complaint they have here in their code is that an exception is being thrown. That means the first thing that needs to be answered is what that exception means and what to do about it. And Stack Overflow is not an appropriate place to deconstruct a whole program full of bugs, helping fix it point by point. Which is what would be needed if we hope to move past that initial issue that the OP has. They really need to break the issues down into one-per-question. – Peter Duniho Sep 20 '20 at 01:54

1 Answers1

0

You're only asking for the option selection once, before the while(true) loop:

string option = Console.ReadLine();

After that, you treat all user input as integers, so there's no opportunity for the user (you) to change the option. One easy fix is to place that line inside the loop, preferably with some more instructions:

//... Your code... 

while(true)
{
   Console.Write("Add, Remove, End: “);
   string option = Console.ReadLine();
  
   switch(option.ToLower())
   {
      //... Your code... 
   } 
}

Now, I'm not convinced that the rest of your program works properly, but that's another story. You can debug it with breakpoints once you get over this hurdle.

CoolBots
  • 4,770
  • 2
  • 16
  • 30