繁体   English   中英

在 C# 中将 String 转换为 int

[英]Convert String to int in C#

我正在尝试编写一个简单的程序,要求用户输入一个数字,然后我将使用该数字来决定他们给定年龄的门票费用。 尝试将字符串转换为 int 时遇到问题。 否则程序布局很好。 有什么建议? 谢谢

using System;

class ticketPrice
{    
    public static void Main(String[] args)
    {
        Console.WriteLine("Please Enter Your Age");
        int input = Console.ReadLine();
        if (input < 5)
        {
            Console.WriteLine("You are "+input+" and the admisson is FREE!");
        }
        else if (input > 4 & input < 18)
        {
            Console.WriteLine("You are "+input+" and the admission is $5");
        }
        else if (input > 17 & input < 56)
        {
            Console.WriteLine("You are "+input+" and the admission is $10");
        }
        else if (input > 55)
        {
            Console.WriteLine("You are "+input+" and the admission is $8");
        }
    }
}

尝试int.TryParse(...)方法。 它不会抛出异常。

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

此外,您应该在条件中使用&&而不是& &&是逻辑与, &是按位与。

  • 为了将字符串轻松解析为整数(和其他数字类型),请使用该数字类型的.TryParse(inputstring, yourintegervariable)方法。 这个方法会输出一个布尔值(真/假),让你知道操作是通过还是失败。 如果结果为假,您可以在继续之前给出错误消息(不必担心程序崩溃)。

  • 之前关于 switch 语句的文本已被删除

  • 在 C# 中,您需要对逻辑 AND 使用&&运算符。 &是不一样的,可能不会像你相信的那样工作。

int number = int.Parse(Console.ReadLine());

请注意,如果他们输入无效数字,这将引发异常。

我建议使用Int32.TryParse()方法。 此外,我建议重构您的代码 - 您可以使其更清晰(假设这不仅仅是示例代码)。 一种解决方案是使用键值对列表来映射从年龄到入学。

using System;
using System.Collections.Generic;
using System.Linq;

static class TicketPrice
{
    private static readonly IList<KeyValuePair<Int32, String>> AgeAdmissionMap =
        new List<KeyValuePair<Int32, String>>
            {
                new KeyValuePair<Int32, String>(0, "FREE!"),
                new KeyValuePair<Int32, String>(5, "$5."),
                new KeyValuePair<Int32, String>(18, "$10."),
                new KeyValuePair<Int32, String>(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));
    }
}

我使用了一个无符号整数来防止输入负年龄并将输入放入循环中。 通过这种方式,用户可以更正无效的输入。

您需要做的第一件事是将input变量更改为字符串:

string input = Console.ReadLine();

一旦你有了它,有几种方法可以将它转换为整数。 有关更多信息,请参阅此答案:
将对象强制转换为 int 的更好方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM