Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Strings to Ints

Alright, nub question. I know. Basic response might be

Convert.ToInt32(string);

But naturally, C# does every natural process to make sure just that doesn't happen.

Here's my code:

            while (true)
            {

                while (true)
                {
                    //ask for time
                    Console.WriteLine("What is the hour?");
                    Console.WriteLine();
                    string s = Console.ReadLine();
                    //convert input to int
                    YourTime.nHour = Convert.ToInt32(s);
                    //check to see if it's legal
                    if ((YourTime.nHour <= 12) || (YourTime.nHour > 0))
                    {
                        break;
                    }
                //etc etc code
                }
            }  

I want to make sure the input is an actual hour. When I run this code, it always labels the if() statement as "true" and breaks, even if I inputted something like -13 or 99.

I'm sure there's a simple replacement for "Convert.ToInt32(s);", but to be honest it seems like I've tried everything. I decided it would be best to follow step-by-step instructions from people who are aware of the code at hand.

[EDIT] - Wrong operator, not the conversion. Thanks to everyone who helped!

like image 242
Tako M. Avatar asked Mar 10 '26 07:03

Tako M.


2 Answers

You need to use AND not OR. So, change it to

if ((YourTime.nHour <= 12) && (YourTime.nHour > 0)) 
like image 107
D'Arcy Rittich Avatar answered Mar 11 '26 20:03

D'Arcy Rittich


It's your if statement that's invalid, not the Convert.ToInt32

if ((YourTime.nHour <= 12) || (YourTime.nHour > 0)) will always be true. I think you meant to do if ((YourTime.nHour <= 12) && (YourTime.nHour > 0))

like image 36
pjumble Avatar answered Mar 11 '26 21:03

pjumble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!