Search code examples
c#boolean-logicboolean-expression

C# Getting user input and outputting to boolean


I am currently in a C# boot camp. I am having trouble putting this together. The assignment is to create a console app for an insurance company that asks three questions.

  1. Age, which must be greater than 15,
  2. any speeding tickets, must be 3 or less, and
  3. DUI's, which must be answered "false". Then
  4. Qualified? with an answer of true / false.

I'm technically not supposed to use "if" statements in the code since we haven't covered "if" statements in the C# course yet so it should be a basic equation to check all 3 user inputs to print out one answer of true/false. I am having issues putting the equation together at the end that checks all three and outputs a true/false answer. This is my first post on here, so, my apologies if I'm not giving the proper info. Any help would be appreciated.

namespace BooleanLogic
{
    class Program
    {
        static void Main(string[] args)
        {
            int age = 15, speed = 3;
            bool DUI = false;

            Console.WriteLine("Welcome to TTA Car Insurance. \nYou will be asked a few questions to determine if you qualify. \n");

            Console.WriteLine("What is your age?");
            age = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Have you ever had a DUI? \nPlease enter true or false.");
            DUI = Convert.ToBoolean(Console.ReadLine());

            Console.WriteLine("How many speeding tickets do you have?");
            speed = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Qualified?");
            

            Console.ReadLine();
        }
    }
}

Solution

  • You can test the conditions in a Boolean expression and write the result to the console directly.

    Console.WriteLine(age > 15 && speed <= 3 && !DUI);
    

    This will print "true" or "false".

    Often people think that Boolean expression must occur in a if- or while- statement or the like. But Boolean expressions are expressions like numeric (arithmetic) expressions and can be used the same way. Instead of returning a number, they return a Boolean value, but this value can be assigned to variables, printed, etc.

    Note that you don't need to initialize the variables, because you are never using these values and overwrite them later anyway. You can also declare the variables where the values are first assigned:

    int age = Convert.ToInt32(Console.ReadLine());
    

    It would however make sense to introduce constants for the conditions

    const int MinimumAge = 16;
    const int MaximumSpeed = 3;
    const bool RequiredDUI = false;
    

    and then test

    bool result = age >= MinimumAge  && speed <= MaximumSpeed  && DUI == RequiredDUI;
    

    This makes it easier to change the conditions and makes the Boolean expression self-explaining.