无法将类型'string'隐式转换为'int'

时间:2015-03-17 00:21:52

标签: c# string int

我正在做一个运动员计划,我想制作int salaryCounter = athleteSalary.ToString,所以当用户输入雇佣专业人员的薪水时,我可以从运动员的工资中减去它并打印出运动员的数量已经离开,但当我尝试这样做时,程序告诉我“不能隐式地将类型'字符串'转换为'int'”。有人能帮助我吗?

{
    Console.WriteLine("Please enter the first name of the athlete");
    String athleteString = Console.ReadLine();
    Console.WriteLine("Please enter the second name of the athlete");
    String athleteString2 = Console.ReadLine();
    Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", athleteString.ToString(), athleteString2.ToString());
    ConsoleKeyInfo KeyInfo = Console.ReadKey();

    if (KeyInfo.KeyChar == 'y')
    {
        Console.WriteLine("Enter the salary of {0} {1}", athleteString.ToString(), athleteString2.ToString());
        String athleteSalary = Console.ReadLine();
        Console.WriteLine("{0} Is this right?", athleteSalary.ToString());
        ConsoleKeyInfo rightathleteSalary = Console.ReadKey();
        int salaryCounter = athleteSalary.ToString();

        if (rightathleteSalary.KeyChar == 'y')
        {
             Console.WriteLine("Ok. Lets contiune.");
             athleteSalary = Convert.ToString(salaryCounter);
             Console.WriteLine(salaryCounter);

             int counter = 0;

             Console.WriteLine("{0} {1} {2}", athleteString.ToString(), athleteString2.ToString(), salaryCounter.ToString());
             Console.WriteLine("Enter the hired help. The max number of people is five. Press any key to start.");

             while (counter < 5)
             {
                 Console.ReadKey();
                 Console.WriteLine("Please enter the first name of the hired help");
                 String hiredhelpString = Console.ReadLine();
                 Console.WriteLine("Please enter the Last name of the hired help");
                 String hiredhelpString2 = Console.ReadLine();
                 Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
                 ConsoleKeyInfo KeyInfo5 = Console.ReadKey();

                 if (KeyInfo5.KeyChar == 'y')
                 {
                     Console.WriteLine("Enter the salary of {0} {1}", hiredhelpString.ToString(), hiredhelpString2.ToString());
                     String hiredhelpSalary = Console.ReadLine();
                     Console.WriteLine("{0} Is this right?", hiredhelpSalary.ToString());
                     ConsoleKeyInfo rightSalary = Console.ReadKey();

                     if (rightSalary.KeyChar == 'y')
                     {
                         Console.WriteLine("Ok. Lets contiune.");
                     }
                     Console.WriteLine("Record this proffesional? Press y for yess n for no.");
                     ConsoleKeyInfo RecordKey = Console.ReadKey();

                     if (RecordKey.KeyChar == 'y')
                     {
                         counter = counter + 1;
                         Console.WriteLine("Number of hired help is {0} They will be paid {1}", counter, hiredhelpSalary);
                         Console.WriteLine("Press any key to contiune.");
                     }
                     else
                     {
                         if (RecordKey.KeyChar == 'n')
                         {
                             counter = counter - 1;
                             Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
                             Console.ReadKey();
                             Console.WriteLine("Please enter the first name of the hired help");
                             String hiredhelpString3 = Console.ReadLine();
                             Console.WriteLine(" Please enter the Last name of the hired help");
                             String hiredhelpString4 = Console.ReadLine();
                             Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
                             ConsoleKeyInfo KeyInfo6 = Console.ReadKey();

                             if (KeyInfo6.KeyChar == 'y')
                             {
                                 Console.WriteLine("Record this proffesional? Press y for yess n for no.");
                                 ConsoleKeyInfo RecordKey1 = Console.ReadKey();
                                 if (RecordKey.KeyChar == 'y')
                                 {
                                     counter = counter + 1;
                                     Console.WriteLine("Number of Hired help is {0} press any key to contiune", counter);
                                     Console.WriteLine("Press any key to contiune.");
                                 }
                             }
                         }
                     }
                            /*******************************************************************************************************/
                            /************************************************************************************************************************************************************************************************************************************************/
                        }
                        else
                        {
                            if (KeyInfo5.KeyChar == 'n')
                            {
                                Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
                                Console.ReadKey();

                            }
                        }
                    }
                    /*************************************************************************************************************************************************************************************************************************************/
                    Console.WriteLine("");
                    Console.WriteLine("Athlete's name: {0} {1} Number of Hired help is {2}", athleteString.ToString(), athleteString2.ToString(), counter);
                    Console.ReadKey();


            }

2 个答案:

答案 0 :(得分:2)

看起来你对变量类型感到困惑。简言之;

string - 逐个字符地存储信息。编译器无法读取存储在字符串中的数字。

int - 存储可用于计算的整数值。

你的直接编译问题来自这一行;

int salaryCounter = athleteSalary.ToString();

您告诉编译器采用altheteSalary这是一个字符串,调用ToString()方法获取字符串表示(当源是字符串时这是不必要的)并将结果存储为整数。

你需要解析字符串以读出这样的数值;

int salaryCounter = int.Parse(athleteSalary)

但是,每当您直接从用户收到输入时,您应该进行防御性编码,因此请使用TryParse而不是int.Parse。这样,如果您的用户输入了Bob&#39;对于他们的工资,你可以显示一个适当的错误;

int salaryCounter;
while(!int.TryParse(athleteSalary, out salaryCounter)
{
    Console.Writeline("The salary should be a number, try again");
    athleteSalary = Console.ReadLine();
}

此外,您可以删除对.ToString()的大多数调用,尤其是在变量已经是字符串的情况下。

答案 1 :(得分:0)

主要问题是您需要将用户输入转换为字符串以外的类型。

有很多方法可以做到这一点,但是由于您正在编写一个严重依赖于用户输入数据的控制台应用程序,并且由于某些数据必须转换为字符串以外的类型,您可以考虑编写一些帮助程序处理一些转换和重试的方法。

我在几个应用程序中成功使用了以下类。基本上,它只是一堆接受字符串'prompt'并从用户返回强类型结果的方法。如果用户输入无效数据,则他们必须再次尝试,直到输入有效的内容:

class UserInput
{
    public static bool GetBool(string prompt)
    {
        bool result;

        List<string> validTrueResponses = 
            new List<string> {"yes", "y", "true", "t", "affirmative", 
                "ok", "okay", "yea", "yeah", "yep"};

        List<string> validFalseResponses = 
            new List<string> {"no", "n", "false", "f", "negative", 
                "never", "not", "nay", "nix"};

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            var input = Console.ReadLine();

            if (validTrueResponses.Any(r => 
                r.Equals(input, StringComparison.OrdinalIgnoreCase))) return true;

            if (validFalseResponses.Any(r => 
                r.Equals(input, StringComparison.OrdinalIgnoreCase))) return false;

            if (bool.TryParse(input, out result)) break;

            Console.WriteLine("Sorry, I don't understand that response. " +
                "Please try again.");
        }

        return result;
    }

    public static string GetString(string prompt)
    {
        if (prompt != null) Console.Write(prompt);
        return Console.ReadLine();
    }

    public static int GetInt(string prompt)
    {
        int input;

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            if (int.TryParse(Console.ReadLine(), out input)) break;
            Console.WriteLine("Sorry, that is not valid. Please try again.");
        }

        return input;
    }

    public static decimal GetDecimal(string prompt)
    {
        decimal input;

        while (true)
        {
            if (prompt != null) Console.Write(prompt);
            if (decimal.TryParse(Console.ReadLine(), out input)) break;
            Console.WriteLine("Sorry, that is not valid. Please try again.");
        }

        return input;
    }
}

然后,我将创建一个简单的类来表示Person,它只有一个名字,姓氏和工资(并覆盖ToString方法以显示名字和姓氏):

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public decimal Salary { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
}

现在我们可以通过创建获取Person名称和工资的方法来减少一些重复的代码。这将提示用户输入信息,然后在提交数据之前让他们有机会纠正它:

private static void GetPersonName(Person person, string typeOfPerson)
{
    if (person == null) throw new ArgumentNullException("person");
    if (string.IsNullOrWhiteSpace(typeOfPerson)) typeOfPerson = "person";

    bool inputIsGood = false;

    while (!inputIsGood)
    {
        person.FirstName = UserInput.GetString(
            string.Format("Please enter the first name of the {0}: ", typeOfPerson));

        person.LastName = UserInput.GetString(
            string.Format("Please enter the last name of the {0}: ", typeOfPerson));

        Console.WriteLine("You entered: {0}", person);
        inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
    }
}

private static void GetPersonSalary(Person person)
{
    bool inputIsGood = false;

    while (!inputIsGood)
    {
        person.Salary = UserInput.GetDecimal(
            string.Format("Enter the salary of {0}: $", person));

        Console.WriteLine("You entered: {0:C}", person.Salary);
        inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
    }
}

这可能看起来像很多代码,但是你可以在应用程序中使用它:

private static void Main()
{
    var athlete = new Person();

    GetPersonName(athlete, "athlete");
    GetPersonSalary(athlete);

    Console.WriteLine("Enter the hired help. The max number of people is five. " +
        "Press any key to start.");

    Console.ReadKey();

    List<Person> hiredHelpers = new List<Person>();

    while (hiredHelpers.Count <= 5)
    {
        bool addAnotherHelper =
            UserInput.GetBool(
                string.Format("There are currently {0} helpers. " +
                    "Do you want to add another (y/n): ",
                    hiredHelpers.Count));

        if (!addAnotherHelper) break;

        Person helper = new Person();

        GetPersonName(helper, "helper");
        GetPersonSalary(helper);

        bool recordHelper = UserInput.GetBool("Do you want to record this " +
            "professional (y/n): ");

        if (recordHelper)
        {
            hiredHelpers.Add(helper);
        }
    }

    Console.WriteLine();
    Console.WriteLine("Athlete's name: {0}, salary: {1:C}.", athlete, athlete.Salary);
    Console.WriteLine("Number of Hired help is: {0}", hiredHelpers.Count);
    Console.WriteLine("Hired help details:");
    hiredHelpers.ForEach(h => 
        Console.WriteLine(" - Name: {0}, Salary: {1:C}", h, h.Salary));

    Console.ReadKey();
}