Console input is not treated correctly

Asked

Viewed 89 times

1

When compiling my code in Visual Studio Professional 2019, it is giving error, for example:

Digite sua idade : 12
Você é adulto

Code:

using System; //Usa A Biblioteca System

public class Idade 
{
    public static void Main() //Inicia a função principal Main
    {

        Console.WriteLine("qual sua idade? "); //Mostra um Texto na tela
        Int32 n1 = Console.Read(); 
        Convert.ToInt32(n1);
        Int32 n2 = n1;
        if (n2 < 10)  {
            Console.WriteLine("Você é Criança");

        }
        if (n2 > 10 && n2 < 18 )
        {
            Console.WriteLine("Você é Adolescente");
        }
        else
        {
            Console.WriteLine("Você é Adulto");
        }
    }
}

1 answer

3


There is one problem that is almost syntax (it is not keeping anywhere the converted value), and another that is reading a key and not a data, read the documentation before using any in your code. Without doing this will always program wrong. You can’t use something without understanding all the details of it. See Difference between Console.Read(); and Console.Readline();.

And even created a variable that does nothing.

The if is wasting resources because it gets separated into two independent then the second will be executed even if it enters the first and does not need it, then the comparison can be simplified because if it did not enter the second it is already certain that a part of the condition of that if is already true.

And in your code if the person is 10 she’s an adult, then that’s a mistake too.

Just out of curiosity, the law states that a person is a 12 year old teenager and not 10.

And there’s another problem that almost everyone misses because typing might fail and this happening your code breaks, but it’s not a clear mistake because most of the time it will work. I chose to leave the code when something went wrong, but you can do whatever you want. see Differences between Parse vs Tryparse and What is the main difference between int. Parse() and Convert.Toint32()?.

I also modernized the code and took the comments because they are Bviedades, this type of comment only disturbs, in this specific case does not serve nor didactic form, even by the inconsistency.

using static System.Console;

public class Idade {
    public static void Main() {
        WriteLine("Qual sua idade? ");
        if (!int.TryParse(ReadLine(), out var n1)) return; 
        else if (n1 < 10) WriteLine("Você é Criança");
        else if (n1 < 18) WriteLine("Você é Adolescente");
        else WriteLine("Você é Adulto");
    }
}

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

  • Thank you so much for the expensive explanation I was really doing without reading the documentation right ! thank you so much!

Browser other questions tagged

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