I am producing a kind of form, but in age people put (age + "years")

Asked

Viewed 40 times

0

I am producing a kind of form, but at age people put (age + "years"), but the variable is type int so it does not work, I wonder if there is any method of sending a message to the customer when he insert a letter in the age field as for example.

int idade;
console.write("idade:");
idade = convert.toint32(console.readline());
if(int nao for numero)
{
   faça alguma coisa;
}

3 answers

1

There are a few ways to do this. The simplest would be with int.TryParse where it will try to convert a string to an integer. If it fails, it returns false and makes no exception. The version int.Parse generates an exception.

Example:

Console.Write("Digite a idade:");
bool isNumber = int.TryParse(Console.ReadLine(), out int idade);
if (isNumber)
{
    // use a variável 'IDADE' aqui
}
else
{
    Console.WriteLine("Digite apenas números para idade");
}

Converts the string representation of a number into the integer with an equivalent 32-bit signal. A returned value indicates if the operation was successful.

Reference: System.Int32.Trypase (msdn)

1


You can do this way, the code is commenting explaining its operation.

using System;

public class Program
{
    public static void Main()
    {       
        int idade;

        // Console e Write são iniciados com letras maiusculas 
        Console.Write("idade:");

        // Console, Read e Line são iniciados com letras maiusculas
        string idadeString = Console.ReadLine();

        // Se foi digitado um número inteiro
        if(Int32.TryParse(idadeString, out idade))
        {
           Console.Write("idade: " + idade);
        }else{
            Console.Write("Favor inserir um valor inteiro");
        }
    }
}

Source

  • very good, I know q if I started with capital letters here in the example I did everything minuscule by the time

-2

I would use an IF:

if(($idade > 0) || ($idade < 99)){
  echo "aqui vai o campo";
} else {  
echo "insira uma idade válida";
}
  • 2

    Josla looks for a reply in C# and not in php, and he wants to identify if a certain value that was typed is integer or not.

Browser other questions tagged

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