在C#中将字符串转换为整数

3

我正在尝试编写一个简单的程序,让用户输入一个数字,然后我将使用该数字来确定他们年龄对应的票价。但是当我尝试将字符串转换为整数时遇到了问题。除此之外,程序布局很好。有什么建议吗?谢谢。

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

1
除了我的回答之外,考虑使用<5 |> = 5 && <18 |> = 18 && <56 |> = 56。这对我来说更容易理解。 - Daniel Brückner
2
可能是如何将String转换为Int?的重复问题。 - crashmstr
规范答案是(39个答案和总投票数超过2000):*如何将字符串转换为整数?* - Peter Mortensen
5个回答

10

&& 和 & 都是逻辑与。 (请参阅 TheTXI 答案上的注释。) - Daniel Brückner

2
  • 为了将字符串轻松解析为整数(和其他数字类型),请使用该数字类型的.TryParse(inputstring, yourintegervariable) 方法。此方法将输出一个布尔值(True/False),让您知道操作是否成功。如果结果为假,您可以在继续之前给出错误消息(无需担心程序崩溃)。

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

  • 在 C# 中,您需要使用 && 运算符进行逻辑 AND 运算。 & 不同,并且可能不会按照您所期望的方式工作。


我不认为在这里使用switch是可行的,因为它不能用于范围(你是想到Visual Basic了吗?)。当然,你可以使用空case穿透,但考虑到示例程序需要55个case语句以及一个默认语句来完成这个任务,你真的认为这是更好的方法吗?? - Greg Beech
我本以为 switch 语句允许使用范围。经过仔细检查,发现实际上并非如此。感谢您提醒我 :) - TheTXI
1
两个运算符 - & 和 && - 都是逻辑 AND 运算符。& 是“真正的”逻辑 AND 运算符,而 && 是条件逻辑 AND 运算符。当 & 总是评估两个操作数时,&& 仅在左操作数评估为 true 时才评估右操作数。因此,这取决于您需要使用哪个。如果操作数没有副作用,并且操作数之间没有依赖关系,则它们是功能等效的(但 && 可能会节省一些操作)。 - Daniel Brückner

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

请注意,如果输入无效数字,此操作将引发异常。


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

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


好的,很棒你指出了OP中需要重构代码的必要性。 - Noldorin

0

你需要做的第一件事是将你的 input 变量转换为字符串:

string input = Console.ReadLine();

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接