3

I am trying to write a simple program that asks the user to enter a number and then I will use that number to decide what the cost of the ticket will be for their given age. I am having trouble when trying to convert the string to int. Otherwise the program layout is fine. Any suggestions? thanks

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

5 Answers 5

10

Try the int.TryParse(...) method. It doesn't throw an exception.

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

Also, you should use && not & in your conditions. && is logical AND and & is bitwise AND.

1
  • && and & are both logical ANDs. (See the comment on TheTXI's answer, too.) Jun 4, 2009 at 20:15
2
  • For easy parsing of strings to integers (and other number types), use that number type's .TryParse(inputstring, yourintegervariable) method. This method will output a Boolean (True/False), letting you know whether the operation passed or failed. If the result is false, you can give an error message before going any further (don't have to worry about crashing your program).

  • Previous text concerning switch statements has been removed

  • In C#, you need to use the && operator for logical AND. & is not the same and may not work the way you believe it will.

3
  • I don't see how switch is applicable here as it cannot be used for ranges (are you thinking of Visual Basic?). Sure you can use empty-case fallthrough, but given that the example program would require 55 case statements plus a default to do this, are you really suggesting that's a better approach??
    – Greg Beech
    Jun 4, 2009 at 19:24
  • I could have sworn the switch statement allowed for ranges. After some double checking it appears that is not the case after all. Thank you for bringing this to my attention :)
    – TheTXI
    Jun 4, 2009 at 19:43
  • 1
    Both operators - & and && - are a kind of logical AND operator. & is the 'real' logical AND operator && is the conditional logical AND. While & always evalutes both operands && evalutes the right operand only if the left operand evaluated to true. So it depends which one you have to use. If the operands have no side effects and there are no dependencies between the operands, they are functional equivalent (but && might save some operations). Jun 4, 2009 at 19:53
1

I suggest to use the Int32.TryParse() method. Further I suggest to refactor your code - you can make it much cleaner (assuming this is not just example code). One solution is to use a key value pair list to map from age to admission.

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

I used an unsigned integer to prevent entering negative ages and put the input into a loop. This way the user can correct an invalid input.

1
  • Yeah, well done for pointing out the need to refactor the code in the OP.
    – Noldorin
    Jun 4, 2009 at 19:40
1
int number = int.Parse(Console.ReadLine());

Be aware that this will throw an exception if they enter an invalid number.

0

The first thing you need to do is change your input variable to a string:

string input = Console.ReadLine();

Once you have that, there are several ways to convert it to an integer. See this answer for more info:
Better way to cast object to int

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.