❔ Can not figure out a way to make my code repeat until you type a valid input
im having a hard time figuring out how to make my code repeat until you enter a number and if you enter a letter or some other character it will just repeat itself
im also kinda new to this so please dont butcher me
11 Replies
Use a loop
A
while
loop, most commonly
And $tryparse to check if the entered value is actually a number. And if so, to get the parsed value outThe TryParse pattern is considered best practice of parsing data from a string:
- a TryParse method returns
true
or false
to inform you if it succeeded or not, so you can use it directly in a condition,
- since C# 7 you can declare a variable that will be used as an out
argument inline in an argument list,
- it forces you to check if the out
argument contains valid data afterwards,
Avoid: Convert.ToInt32 — it's a bad choice for parsing an int
. It exists only for backwards compatibility reasons and should be considered last resort. (Note: Convert does contain useful conversion methods: To/FromBase64String
, To/FromHexString
, ToString(X value, int toBase)
, ToX(string? value, int fromBase)
)
Avoid: int.Parse — you have to use a try
/catch
statement to handle invalid input, which is a less clean solution.
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__ Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
how do I add the while loop in the code
Just... do
Write it
huh?
Adding a while loop is no different than adding any other piece of code
Just stroke the keys on your keyboard to input proper symbols that make up valid syntax
there's a learning module on while loops if you need it
Add looping logic to your code using the do-while and while stateme...
Use the
do-while
and while
statements to iterate as long as a Boolean expression evaluates to true.while (adden1 != double)
is the only thing that comes to my mind and it doesnt workI told you to use
TryParse()
since it returns a boolean
The bot even posted more explanationWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.