Doubt Console.Readline

Asked

Viewed 476 times

3

The user typed this in the console:

adicionartempo;(qualquer número que ele digitou)
string adicionartempo = Console.ReadLine();

After typing this, how can I get the number he typed and type in the Console.Writeline? This way:

Console.WriteLine("O tempo (numero que ele digitou) foi adicionado")

2 answers

3


You have to convert the value to integer, see:

using System;
                    
public class Program
{
    public static void Main()
    {
        int tempo = 0;
        
        if (int.TryParse(Console.ReadLine(), out tempo))            
            Console.WriteLine("O tempo {0} foi adicionado", tempo);            
        else 
            Console.WriteLine("Valor inteiro inválido");
    }
}

Entree:

10

Exit:

Time 10 has been added

The method TryParse does it for you.

See working on .NET Fiddle.

Editing

After clearing the AP’s doubt in chat I worked out this solution:

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Comando: ");
        
        var comando = Console.ReadLine();
        
        if (VerrificarComando(comando))
        {
            var tempo = 0;
            
            if (int.TryParse(Regex.Match(comando, @"\d+").Value, out tempo))
            {
                Console.WriteLine("O tempo {0} foi adicionado", tempo);
                
                return;
            }
            
            Console.WriteLine("Valor inteiro inválido");
        }        
        
        Console.WriteLine("Comando inválido");
    }
    
    static bool VerrificarComando(string comando)
    {                    
        return Regex.Match(comando, @"\b(adicionartempo)\b").Success;
    }
}

See working on .NET Fiddle.

  • Can it be in this format?: add time;(any number he has typed) In case the person would have to type add time; before typing the number

  • @Betadarknight you want a function, like AdicionarTempo()?

  • No, the person would have to type add-time; before typing the number to be executed

  • @Betadarknight as if it were some kind of option?

  • Yes, example: additiontime1;(time 1), additiontime2;(time 2) and so on

  • @Betadarknight gives a look, I edited the answer.

  • Wouldn’t you be able to put everything together? When writing the add time already add time?

  • But time is informed by the user or is a random value?

  • Informed by the user

  • But that’s what the program does, the user enters the add-time command and then informs the time.

Show 6 more comments

2

  • Can it be in this format?: add time;(any number he has typed) In case the person would have to type add time; before typing the number

Browser other questions tagged

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