Challenge: Safe Parsing for User Input
Swipe to start coding
Implement a method that safely parses string input for a product price and quantity. Your method should use TryParse to convert the price to a decimal and the quantity to an int, and return a message indicating the result.
- Attempt to parse
priceInputas a decimal. - Attempt to parse
quantityInputas an int. - If both values are invalid, return
"Invalid price and quantity input.". - If only
priceInputis invalid, return"Invalid price input.". - If only
quantityInputis invalid, return"Invalid quantity input.". - If both values are valid, return a message in the format:
"Total cost for {quantity} items at {price:C} each is {total:C}.", where{price}is the parsed decimal,{quantity}is the parsed int, and{total}is the product of price and quantity.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain this in simpler terms?
What are the main benefits or drawbacks?
Can you give me a real-world example?
Awesome!
Completion rate improved to 4.17
Challenge: Safe Parsing for User Input
Swipe to show menu
Swipe to start coding
Implement a method that safely parses string input for a product price and quantity. Your method should use TryParse to convert the price to a decimal and the quantity to an int, and return a message indicating the result.
- Attempt to parse
priceInputas a decimal. - Attempt to parse
quantityInputas an int. - If both values are invalid, return
"Invalid price and quantity input.". - If only
priceInputis invalid, return"Invalid price input.". - If only
quantityInputis invalid, return"Invalid quantity input.". - If both values are valid, return a message in the format:
"Total cost for {quantity} items at {price:C} each is {total:C}.", where{price}is the parsed decimal,{quantity}is the parsed int, and{total}is the product of price and quantity.
Solution
Thanks for your feedback!
single