views:

536

answers:

5

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");
        }
    }
}
+1  A: 

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

// be aware that this will throw an exception if they enter an invalid number

John JJ Curtis
+11  A: 

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.

Daniel A. White
Daniel Brückner
+2  A: 
  • For easy parsing of strings to intgers (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.

TheTXI
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
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
Daniel Brückner
A: 

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:
http://stackoverflow.com/questions/745172/better-way-to-cast-object-to-int/745204#745204

Joel Coehoorn
+1  A: 

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.

Daniel Brückner
Yeah, well done for pointing out the need to refactor the code in the OP.
Noldorin