3

我正在尝试编写一个简单的程序,要求用户输入一个数字,然后我将使用该数字来决定他们给定年龄的门票费用。尝试将字符串转换为 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");
        }
    }
}
4

5 回答 5

10

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

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

此外,您不应该&&&您的条件下使用。&&是逻辑与并且&是按位与。

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

  • 先前有关 switch 语句的文本已被删除

  • 在 C# 中,您需要使用&&运算符进行逻辑与。&不一样,可能不会按照您认为的方式工作。

于 2009-06-04T19:10:35.187 回答
1

我建议使用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));
    }
}

我使用无符号整数来防止输入负年龄并将输入放入循环中。这样,用户可以更正无效的输入。

于 2009-06-04T19:37:23.463 回答
1
int number = int.Parse(Console.ReadLine());

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

于 2009-06-04T19:05:27.757 回答
0

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

string input = Console.ReadLine();

一旦你有了它,有几种方法可以将它转换为整数。有关更多信息,请参阅此答案:
Better way to cast object to int

于 2009-06-04T19:12:51.407 回答