Customers of 65 years and over are entitled to discount of 20% on all purchases from an online shopping site. Write compile and test a program which will read in a customer’s age, and inform them whether or not they are entitled to discount on purchases.

I have this so far

namespace Practise1d
{
    class Program
    {
        static void Main(string[] args)
        {
            int age = 0;
            Console.WriteLine("Please enter your age:");
            Console.ReadLine();

            if (age >= 65)
            {
                Console.WriteLine("You are entitled to discount");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("You are not entitled to discount");
                Console.ReadLine();
            }
        
        }
    }
}

no mater what age I put in it says you are not entitled to discount.

Recommended Answers

All 4 Replies

age is never set to anything other than 0. What you probably wanted was something more like this:

int age;

Console.Write("Please enter your age: ");

if (int.TryParse(Console.ReadLine(), out age))
{
    if (age >= 65)
    {
        Console.WriteLine("You are entitled to discount");
        Console.ReadKey(true);
    }
    else
    {
        Console.WriteLine("You are not entitled to discount");
        Console.ReadKey(true);
    }
}
else
{
    Console.WriteLine("Invalid age");
}

You need to convert the result from the ReadLine() into the integer.
You need to set "age" to a value other than zero.

In C# you read an integer with

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

:P That should answer some more questions in case you have them. Was stuck at the same problem when i started with C#.

Good luck!

In C# you read an integer with

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

:P That should answer some more questions in case you have them. Was stuck at the same problem when i started with C#.

Good luck!

int.Parse() will throw an exception if the string is null or doesn't represent a valid integer. It's not safe to assume that Console.ReadLine() will return anything usable by int.Parse(). You could wrap the whole thing in a try..catch, but that's kind of a waste when TryParse() avoids any need for exception handling.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.