Integer reading via console

Asked

Viewed 202 times

0

Good evening, folks. 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 reading of the speed variable does not come out according to what was typed. Example: if I type 240 nodes, the variable receives only 50. Soon the conversion of nodes to km/h leaves with wrong result.

Does anyone give a help to Noob here ? rs

2 answers

5

What happens is that the Console.Read reads only one character and converts it to decimal according to the ascii table, in your case by reading 2 and converting to 50. Instead, use the 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 the int.TryParse to verify that the user is entering valid data for an integer number.

  • I think we missed the !

  • @LINQ I was on smartphone haha, I have not tested. I have edited, thank you! =)

  • It worked @Francisco. Thanks for the touch with int.Tryparse ;)

0


Good morning. To simplify just use Console.Readline(); because Read() only reads one character, one buffer, and Readline() reads every line until it finds an indicator that has reached the end of the line. Compare item 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();
    }
}
  • Worked perfectly now. :)

Browser other questions tagged

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