0

I am basically trying to continue a loop until user enters the required input. I got it to work if less than 1 or greater than 7 is input. But I still get an "Unhandled Exception" error if user inputs either space characters or just hits ENTER. Any help or suggestion is greatly appreciated.

Here is the code-

   static void Main(string[] args)
    {
        string[] daysOfWeek = {
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
        };

        System.Console.WriteLine("  Which day would you like?");
        System.Console.Write("  Choose from 1 and 7. ");
        int? iDay = int.Parse(Console.ReadLine());

        // Loops until user enters number from 1 - 7
        while ( iDay < 1 || iDay > 7 || iDay is null )
        {       
                if ( iDay > 0 && iDay < 8)
                {
                    break;
                }
            System.Console.Write("  < INVALID - CHOOSE FROM 1 AND 7 > ");
            iDay = int.Parse(Console.ReadLine()); 
        }

            string chosenDay = daysOfWeek[(int)iDay-1];
            System.Console.WriteLine($"You chose {chosenDay}.");
        
1
  • 1
    Use an int.TryParse instead of int.Parse... Int32.TryParse Method Commented Nov 8, 2020 at 4:32

1 Answer 1

1

Use int.TryParse

bool isValid = int.TryParse(Console.ReadLine(), out int iDay);

// Loops until user enters number from 1 - 7
while (!isValid || iDay < 1 || iDay > 7)
{
    // This is redundant to the while clause
    //if (iDay > 0 && iDay < 8)
    //{
    //    break;
    //}
    System.Console.Write("  < INVALID - CHOOSE FROM 1 AND 7 > ");
    isValid = int.TryParse(Console.ReadLine(), out iDay);
}
Sign up to request clarification or add additional context in comments.

1 Comment

do this instead while(!int.TryParse(Console.ReadLine(), out int iDay) && (iDay < 1 || iDay >7))

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.