Integer reading via console

0

Good evening, everyone. A basic question:

In the code below

    class Conversora
    {
        double Oneknot = 1.852; // km/h


    public void Conversor(){

        Console.WriteLine("Informe a velocidade em nós: " );
        int speed = Console.Read();
        Console.WriteLine("A velocidade em km/h é de: " + Oneknot * speed);

        Console.ReadKey();
    }

The speed variable does not read as it was typed. Example: if I type 240 nodes, the variable receives only 50. Then the conversion of nodes to km / h leaves with the wrong result.

Does anyone give a help pro noob here? rs

    
asked by anonymous 26.10.2017 / 04:43

2 answers

0

Good morning. For simplicity just use Console.ReadLine (); because Read () reads only one character, a buffer, and ReadLine () reads the entire line until it finds an indicator that has reached the end of the line. Comparison heading make the account with a calculator. see more in this reference:

Difference between Console.Read (); and Console.ReadLine ();

 class Conversora
{
    double Oneknot = 1.852; // km/h


    public void Conversor()
    {

        Console.WriteLine("Informe a velocidade em nós: ");
        int speed = Convert.ToInt32( Console.ReadLine());
        Console.WriteLine("A velocidade em km/h é de: " + Oneknot * speed);

        Console.ReadKey();
    }
}
    
26.10.2017 / 14:36
5

What happens is that Console.Read reads only one character and converts it to decimal according to the ascii table, in your case, reading 2 and converting to 50. Instead use Console.ReadLine() :

class Conversora
{
    double Oneknot = 1.852; // km/h

    public void Conversor()
    {
        int speed;
        do{
            Console.WriteLine("Informe a velocidade em nós: " );
        }
        while(!int.TryParse(Console.ReadLine(), out speed));
        Console.WriteLine("A velocidade em km/h é de: " + Oneknot * speed);
        Console.ReadKey();
    }
}

Use int.TryParse to verify that the user is putting valid data for an integer.

    
26.10.2017 / 04:52