Proper use of while to validate data entry

Asked

Viewed 295 times

3

I’m trying to apply a repetition using the while also using the IF condition, which returns a message to the user if they enter an invalid value. Note that I write nothing inside the while, but the code works exactly as I hope. Despite this, the fact that I have not put anything inside the while It makes me sick, it feels wrong somehow. Could you consider whether it’s the most appropriate or whether there’s a better way to solve situations like this?

    string dia;
            string mes;

            do
            {
                Console.WriteLine("Em que dia você nasceu?");
                dia = Console.ReadLine();

                if (Convert.ToInt32(dia) > 31)

                {
                    Console.WriteLine("Digite dia válido");
                }
            }

            while (Convert.ToInt32(dia) > 31);
            {
//repare que aqui eu não escrevo nada
            }

            do
            {
                Console.WriteLine("Em que mês você nasceu?");
                mes = Console.ReadLine();
                if (Convert.ToInt32(mes) > 12)

                {
                    Console.WriteLine("Digite mês válido");
                }
            }

            while (Convert.ToInt32(mes) > 12);
            {
               //repare que aqui eu não escrevo nada

            }

2 answers

6


using static System.Console;

public class Program {
    public static void Main() {
        while (true) {
            WriteLine("Em que dia você nasceu?");
            if (int.TryParse(ReadLine(), out var dia) && dia < 32) break;
            WriteLine("Digite dia válido");
        }
        while (true) {
            WriteLine("Em que mês você nasceu?");
            if (int.TryParse(ReadLine(), out var dia) && dia < 13 break;
            WriteLine("Digite mês válido");
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Test with invalid data also.

This is the simplest and most correct way to make this code. Even if another way works in a quick test, it will not work in any case.

This loop you are creating is unnecessary and even the code you used before is more complex than it should be. Note that I simplified a lot even adding a validation if the data was typed correctly. In the loop I made I test the validity of the typing, if it’s ok leave the loop, if it doesn’t pass the test it keeps repeating.

Never repeat codes that say the same thing. When you have more than once the same code that is a business rule runs the risk of in a maintenance forget to change the other. The form I wrote has only once the conversion and validation of the data.

Note that this has logic error. He should ask first the month of birth, and then the day. Why? The correct validation of the day depends on the month you were born. If it is January, this code is ok, just like March, May, etc. But if it is April, June, etc. a number 31 is invalid and this should be picked up. You can only do this after you know what month it is. Needless to say, February can only be up to 28 or 29 if it is leap.

Of course, if the user experience asks to type in this order then ask for the two data and only then do the validation.

Fix this logic as exercise.

  • Dude, what an amazing answer! I’m going to apply this logic here and I’ll also do the exercise you proposed. Thank you so much for clarifying my question.

  • 1

    If you have specific questions about the improvement you make you can post here that we help.

  • To implement the modifier out in my github project.com/gebueno/Minhacalculadoradesignos I will have to modify the methods that receive the values of day and month, correct? I tried all night to understand how this modifier works but I couldn’t apply to my project.

  • 1

    @Gersonbueno https://answall.com/q/82630/101 see if it helps. Almost everything you want to know has been answered here. If you don’t have an opportunity to ask a new question.

2

That "supposed" block while that you mentioned does absolutely nothing, it would be like using parentheses like this:

int x = 1 + 1;  
// ou
int x = (1 + 1);

Note that while is part of the command do, that is, the keys { } are not of the structure of while, they are there doing nothing of their example.

The fact of closing the while with ; it would already indicate that it closed the structure, and the keys do not belong to the command, but I suggest to study better the structure of the do and of while.

It would make sense if the command were like this:

while (Convert.ToInt32(dia) > 31)
{
    Console.WriteLine("Em que dia você nasceu?");
    dia = Console.ReadLine();

    if (Convert.ToInt32(dia) > 31)

    {
        Console.WriteLine("Digite dia válido");
    }
}
  • Thanks for helping! This block you wrote tries to compare a variable that doesn’t have value yet, hence gives error "variable with no value assigned"...

  • 1

    is an example of while without the do, the idea was not to rewrite the whole code but to show where the problem was with the while ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.