Convert String to int in C#

前端 未结 5 1890
星月不相逢
星月不相逢 2020-12-11 08:10

I am trying to write a simple program that asks the user to enter a number and then I will use that number to decide what the cost of the ticket will be for their given age.

5条回答
  •  长情又很酷
    2020-12-11 08:30

    I suggest to use the Int32.TryParse() method. Further I suggest to refactor your code - you can make it much cleaner (assuming this is not just example code). One solution is to use a key value pair list to map from age to admission.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    static class TicketPrice
    {
        private static readonly IList> AgeAdmissionMap =
            new List>
                {
                    new KeyValuePair(0, "FREE!"),
                    new KeyValuePair(5, "$5."),
                    new KeyValuePair(18, "$10."),
                    new KeyValuePair(56, "$8.")
                };
    
        public static void Main(String[] args)
        {
            Console.WriteLine("Please Enter Your Age!");
    
            UInt32 age;  
            while (!UInt32.TryParse(Console.ReadLine(), out age)) { }
    
            String admission = TicketPrice.AgeAdmissionMap
                .OrderByDescending(pair => pair.Key)
                .First(pair => pair.Key <= age)
                .Value;
    
            Console.WriteLine(String.Format(
                "You are {0} and the admission is {1}",
                age,
                admission));
        }
    }
    

    I used an unsigned integer to prevent entering negative ages and put the input into a loop. This way the user can correct an invalid input.

提交回复
热议问题