Frage

thank you in advance that helps me out! So I've got a pretty simple application and am trying to define the alphabet or any commonly keyboard keys into a comparative expression for an Else IF statement. IF thats even possible without writing a separate block of code. I'm trying to compare the users input "age" to something that wouldn't be an integer so that if they enter a letter or special character it will either loop back or just ignore the request and provoke the chosen text for the Else IF. The question marks are representing what I can't quite figure out. I've looked on MS's dev site and looked all over google. Perhaps I'm not quite googling it the right way or not many people have needed to do this; that aside if anyone could help me I'd greatly appreciate it.

    {
        Console.Write("Please enter your age ");
        string agestring = Console.ReadLine();
        int age;
        var array = ()

        if (Int32.TryParse(agestring, out age))
        {
            if (age >= 21)
            {
                Console.WriteLine("congrats, you can get drunk!");
            }

            else if (age < 21)
            {
                Console.WriteLine("Sorrrrrryyyyyyy =(");
            }

        }
        else if (age != ????)
        {
            Console.WriteLine("Sorry Thats not a valid input, Please enter a correct number.");

        }

    }
  }
}
War es hilfreich?

Lösung

Use a while statement

 while(true) 
 {
    Console.Write("Please enter your age ");
    string agestring = Console.ReadLine();
    int age;
    var array = ()

    if (Int32.TryParse(agestring, out age))
    {
        if (age >= 21)
        {
            Console.WriteLine("congrats, you can get drunk!");
        }

        else if (age < 21)
        {
            Console.WriteLine("Sorrrrrryyyyyyy =(");
        }
        //If you want the program to exit after a valid input, break to get out of loop
        break;

    }
    else if (age != ????)
    {
        Console.WriteLine("Sorry Thats not a valid input, Please enter a correct number.\n");

    }
}

Not sure why you need that var array = (), and it's also an invalid declaration

Andere Tipps

string agestring = "";
int age = 0;

while ( !Int32.TryParse ( agestring, out age ) )
{
    Console.Write ( "Please enter your age: " );
    agestring = Console.ReadLine ( );
}

if ( age >= 21 )
    Console.WriteLine ( "congrats, you can get drunk!" );
else
    Console.WriteLine ( "Sorrrrrryyyyyyy =(" );
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top