Home > Net >  Summary of all numbers (int)
Summary of all numbers (int)

Time:02-20

I have a problem with writing the code, which will be after entering the word "sum", it will add up all the amounts written out and give the net and gross prices. I will be grateful for the hint, and not for solving the task for me.

class Kasa
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Podaj kod produktu");

        while (true)
        {
            try
            {
                string productcode = Console.ReadLine();
                string code = productcode.Substring(0, 1);
                double number = Convert.ToInt64(productcode.Substring(1));

                //Console.WriteLine(code);
                //Console.WriteLine(number);
                //Console.WriteLine(productcode);

                if (code == "a" || code == "A")
                {
                    Console.WriteLine("do zapłaty "   number / 100   ",00 zł");
                    break;
                }

                if (code == "b" || code == "B")
                {
                    //Console.WriteLine((.08 * number)   number);
                    Console.WriteLine("do zapłaty "   ((8 * number / 100)   number)   " zł");
                    break;
                }
                else
                {
                    //Console.WriteLine((.023 * number)   number);
                    Console.WriteLine("do zapłaty "   ((23 * number / 100)   number) / 10   " zł");
                    break;
                }
            }
            catch (FormatException)
            {
                Console.WriteLine("UWAGA! Podaj właściwy kod");
                continue; 
            }
        }
    }
}

CodePudding user response:

Because it can not convert a string to a number, you said that :

double number = Convert.ToInt64("a");

but this code not working

CodePudding user response:

Firstly, if you use substring(0,1) you can only use 1 char as the code. If you want to use "sum" then you need substring(0,3) but what happens when you want to add more code variants? the wise thing is to separate the code and the numbers using delimiter. For example, your input:

sum 100 150 200

Here you can separate your input using " " or whitespace and assign it into an array using delimiter. The index 0 of the array is always the code, be it "sum", "a", "b" or whatever you want.

The next indexes are always numbers, With this info you can do a loop from index 1 to n and convert each string number into an integer number and add them into a new numbers array.

Then you just need to feed that numbers array that contains all the integers into a new function that sums them all up and returns the result.

  • Related