0

Every time I try and input the number of sales. Input string was not in a correct format when running this method.

int numberOfSales = 0;
double[] sales;
Console.Write("Please enter number of sales: ");
numberOfSales = Convert.ToInt32(Console.ReadLine());
sales = new double[numberOfSales];

for (int i = 0; i < numberOfSales; i++)
{

   Console.Write("Please enter  sales #{0}:", i + 1);

   sales[i] = Convert.ToDouble(Console.ReadLine());
}

double sum = sales.Sum();

for (int i = 0; i < numberOfSales; i++)
{

   double contrubution = sales[i] / sum;

   Console.WriteLine("Sale # {0} was {1:C2} and contributed {2P:P2}", i + 1, sales[i], contrubution);
}

Console.WriteLine("Total sum of sales is {0:C2}", sum);

enter image description here

1 Answer 1

2

Your problem is with (and may not be limited to) 2P.

The Background

The braces in a string.Format denotes a Format Item. They are represented by a Token Number followed by and optional : and a Format Specifier.

Token Number {0} is the Index of the object whose string value will be inserted at that position.

The Solve

As you can see in your code you have {2P:P2} which doesn't start with a format Item Number. It should be {2:P2}

Console.WriteLine("Sale # {0} was {1:C2} and contributed {2:P2}", i + 1, sales[i], contrubution);

Additional

May i suggest string interpolation which was introduced in C#6 instead, its easier to read, and less likely you'll make a mistake like this

Console.WriteLine($"Sale # {(i + 1)} was {sales[i]:C2} and contributed {contrubution:P2}");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.