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");
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    Besides my answer think about using < 5 | >= 5 && < 18 | >= 18 && < 56 | >= 56. This seems much more understandable to me. – Daniel Brückner Jun 04 '09 at 20:41
  • 2
    possible duplicate of [How can I convert String to Int?](http://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – crashmstr Aug 12 '15 at 17:00
  • The canonical is (39 answers and a vote total of more 2000): *[How can I convert String to Int?](https://stackoverflow.com/questions/1019793)* – Peter Mortensen Jun 09 '21 at 15:13

5 Answers5

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.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheTXI
  • 37,429
  • 10
  • 86
  • 110
  • 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 04 '09 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 04 '09 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). – Daniel Brückner Jun 04 '09 at 19:53
1
int number = int.Parse(Console.ReadLine());

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

bluish
  • 26,356
  • 27
  • 122
  • 180
jjxtra
  • 20,415
  • 16
  • 100
  • 140
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.

Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
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

Community
  • 1
  • 1
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794