0

So in my car store program I've been trying to find a way to throw an exception when people enter an invalid character more than one time, so I decided to try and use a while loop for when the Console.ReadLine() == null, but can't quite seem to figure it out. Thanks for the help. I only included a snippet of my attempt at a try catch with the while loop.

Console.Out.WriteLine("What is the car make? Toyota, Ford, etc.");

carMake = Console.ReadLine();

Console.Out.WriteLine("What is the car model? Corvette, Focus, etc.");

carModel = Console.ReadLine();

Console.Out.WriteLine("What is the car price? Only numbers please.");
                        
try
{
carPrice = int.Parse(Console.ReadLine());
}
                    
catch

{
while (Console.ReadLine() == null)
{

Console.Out.WriteLine("You must ONLY enter numbers");

carPrice = int.Parse(Console.ReadLine());

}
}
3
  • Please format your code properly. There's no good reason to leave a big wad of leading whitespace that forces us to scroll horizontally to see the code, especially when you obviously removed it from the first line. If you'd like us to take the time to help you, you should do the same for us. Commented Sep 14, 2022 at 5:48
  • 2
    A tip, check How do I format my code blocks, using fences, i.e. ` ``` ` at the start and end of a block is easier than indenting all the code. We usually also expect code inside blocks to be indented, even if this is kind of a pain, but can be made easier by removing extra indentation in your editor before copy-pasting. Commented Sep 14, 2022 at 6:21
  • welcome to stackoverflow JCDeveloper! if you think fixing indentation too bothersome, you can use online code beautifier to fix it - though, if you code in Visual Studio or Visual Studio Code, you can use the built-in auto indent function really. in regard to error handling inside a loop, depends on whether you wanted a fail fast (exit the loop on the first exception) or fail safe (suppress the exception and do alternative flow). Commented Sep 14, 2022 at 8:35

1 Answer 1

3

Use TryParse instead of parse, removing the need for exception handling:

Console.WriteLine("What is the car price? Only numbers please.");
while(!int.TryParse(Console.ReadLine(), out var carPrice)){
    Console.Out.WriteLine("You must ONLY enter numbers");
}

It might also be a good idea to put a code fragment like that into a helper function to read numbers from the console.

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.