Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Safe Parsing for User Input | Validating Input and Safe Parsing
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
C# Exceptions and Error Handling Practice

bookChallenge: Safe Parsing for User Input

Task

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 priceInput as a decimal.
  • Attempt to parse quantityInput as an int.
  • If both values are invalid, return "Invalid price and quantity input.".
  • If only priceInput is invalid, return "Invalid price input.".
  • If only quantityInput is 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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain this in simpler terms?

What are the main benefits or drawbacks?

Can you give me a real-world example?

close

bookChallenge: Safe Parsing for User Input

Swipe to show menu

Task

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 priceInput as a decimal.
  • Attempt to parse quantityInput as an int.
  • If both values are invalid, return "Invalid price and quantity input.".
  • If only priceInput is invalid, return "Invalid price input.".
  • If only quantityInput is 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

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 4
single

single

some-alt