在C#中将String转换为int

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

using System; class ticketPrice { public static void Main(String[] args) { Console.WriteLine("Please Enter Your Age"); int input = Console.ReadLine(); if (input  4 & input  17 & input  55) { Console.WriteLine("You are "+input+" and the admission is $8"); } } } 

尝试int.TryParse(...)方法。 它没有抛出exception。

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

此外,您应该在您的条件下使用&& not &&&是逻辑AND和&是按位AND。

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

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

  • 在C#中,您需要使用&&运算符进行逻辑AND。 &不一样,可能不会像你认为的那样工作。

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

 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)); } } 

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

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

请注意,如果输入的数字无效,则会抛出exception。

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

 string input = Console.ReadLine(); 

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