CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Oct 2012
    Posts
    4

    Question Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Hi All!

    I am learning C# on my own. I have no programming background. I hope to Learn c# to be a .net developer, and earn a decent livelihood in IT.

    Here is a scenario, i wrote the code on:

    Question: Write a program to add two numbers

    Code

    using System;
    using System.Collections.Generic;
    using System.Text;


    namespace AddTwoNumbers
    {
    class Program
    {
    static void Main(string[] args)
    {
    int a,b,c;

    Console.WriteLine("Hi! I am here to add two numbers for you!");
    Console.WriteLine("Enter your first number:");


    a = Int32.Parse(Console.ReadLine());
    Console.WriteLine("Enter You second Number:");

    b = Int32.Parse(Console.ReadLine());
    c = a + b;
    Console.WriteLine("the sum="+c);
    Console.ReadKey();
    Console.WriteLine("thank you!!!");
    Console.ReadKey();

    }
    }
    }


    Doubts:

    1. How and where do I add an warning of sorts if in case someone inputs a alphabet instead of numbers for the addition?

    2. How do Repeat the whole process of addition after "thank you" instead of the console screen just disappearing after readkey?

    3. Why do we write write +c (In "the sum=) instead of just a normal C?

    Many thanks,
    Dawnz

  2. #2
    Join Date
    Jul 2012
    Posts
    90

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    I'm going to answer these in order of difficulty - not the order that they were asked:

    3. Why do we write write +c (In "the sum=) instead of just a normal C?

    The + operator in C# doubles as both the arithmetic addition operator and the string concatination operator. So "First string " + "Next string" results in a single string containing "First string Next string".

    2. How do Repeat the whole process of addition after "thank you" instead of the console screen just disappearing after readkey?

    You will need to use a loop with a triggered escape. Decide on a specific user input to represent the fact that the user is finished and ready to quit. Inside the loop check inputs for this value and exit the loop when it is detected.

    1. How and where do I add an warning of sorts if in case someone inputs a alphabet instead of numbers for the addition?

    You will need to add a few more steps to the process to make this happen. Currently you are in a single statement aquiring data from the user and attempting to convert it to an Int32. You will need to:

    a. aquire the data in a string

    b. check it for validity (contains a number)

    c. if valid - convert to Int32, if not - alert user to mistake (at this point you can use the continue command to skip the remainder of the loop iteration and start over)

    I'm leaving here soon. If no example has been posted, once I get home, I will post one.
    Last edited by CGKevin; October 29th, 2012 at 11:30 AM.

  3. #3
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    OK. But first, please use the [code][/code] tags when posting code - this will preserve existing formatting (but it will not format unformulated code). It's important because it's easier for everyone to read and understand, and you're more likely to get help if the code is readable.

    So, let me take care of that this time:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace AddTwoNumbers
    {
        class Program
        {
            static void Main(string[] args)
            {
                int a,b,c;
    
                Console.WriteLine("Hi! I am here to add two numbers for you!");
                Console.WriteLine("Enter your first number:");
    
                a = Int32.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter You second Number:");
    
                b = Int32.Parse(Console.ReadLine());
                c = a + b;
    
                Console.WriteLine("the sum=" + c);
                Console.ReadKey();
                Console.WriteLine("thank you!!!");
                Console.ReadKey();
    
            }
        }
    }
    Q1 - How and where do I add an warning of sorts if in case someone inputs a alphabet instead of numbers for the addition?

    It's good that you're thinking about that. In situations like this, you have to make a few decisions about how you want your application to work. Do you exit the app if the user provides invalid input, or do you give him another chance? Do you maybe fallback to a default value if the input is not adequate? How do you inform the user about this?

    Lets assume that the app should work like this:
    1. Ask user to enter a number.
    2. Get input.
    3. If not valid -> show error message, then jump back to (1.)
    4. If valid -> continue on.


    Since you've said that you've just started learning C# (and programming in general) you might not yet be familiar with control flow statements that enable you to do this - but don't worry, it's nothing complicated.

    Let's focus on checking if the input is valid or not first. C# provides what's called a conditional statement, or an if-statement. It looks like this:

    Code:
    if (some_condition)
    {
        // do this if some condition evaluates to true
        // if not, just skip to (the rest of the code)
    }
    
    // (the rest of the code)
    Or like this:

    Code:
    if (some_condition)
    {
        // do this if some condition evaluates to true
    }
    else
    {
        // otherwise do this
    }
    
    // (the rest of the code)
    This can be used to check if the input is valid, and I'll show you how in a moment. But first, take a look at this line:
    a = Int32.Parse(Console.ReadLine());

    What happens here is that Console.ReadLine() gets a string (of characters - i.e. text) from the user, which may or may not be a string representation of a number. That string is then passed to the Int32.Parse() method as a parameter. The line of code above is equivalent to this:
    string input = Console.ReadLine();
    a = Int32.Parse(input);


    The Int32.Parse() method then tries to parse that string, figuring out if it represents a number or not. If it does, it returns that number as an integer (type int, the type of the variable a), a numeric data type your application can work with.
    If it does not it does something you're not familiar with yet - it throws an exception. Exceptions are a part of an error handling mechanism, which causes the application to break out of its normal flow (normal execution stops). Programmers normally write code to handle these exceptions - either by trying to recover, or by gracefully informing the user about the error and terminating the app, depending on the situation.
    However, that's not what you're going to do now - you'll do that once you learn more about C#.
    For now, I'm gonna tell you that there's another variant of the Int32.Parse() method called Int32.TryParse(), which does not throw an exception, but returns a Boolean value which indicates if the conversion was successful or not.
    Boolean type variables (type bool) can have only two values - true or false, as you might already know. These can be used as the conditions in an if-statement.

    Now, TryParse() is used a bit differently than Parse():


    string input = Console.ReadLine();
    int number;
    bool conversionOK = Int32.TryParse(input, out number);

    // after the previous line, number should contain the value provided by the user


    Basically, the TryParse() function now doesn't return the number, but it returns the success indicator. Instead of doing it the standard way, it uses an output parameter (note the out keyword) to "return" the number in a different way. You'll learn about output parameters later on.

    What's important to know is that now you can do this:
    Code:
                Console.WriteLine("Hi! I am here to add two numbers for you!");
                Console.WriteLine("Enter your first number:");
    
                bool conversionOK  = Int32.TryParse(Console.ReadLine(), out a);
    
                if (conversionOK == false)
                {
                    Console.WriteLine("Error: Your input was invalid.");  // inform the user of the error
                }
    Now onto the second part - how to repeat the process in the case of error. Well, meet the while-loop.
    Code:
    while (some_contition)
    {
        // repeat this code block as long as some_contition evaluates to true
        // Note1: if some_contition == false to begin with, this block never executes
        // If some_contition is true, and it never becomes false, this loop will run forever! Not good!
    }
    So, all you need to do is create a bool variable to be used as the condition of the while-loop, and modify it to indicate if the program should ask for the input again or not. Like this:
    Code:
            Console.WriteLine("Hi! I am here to add two numbers for you!");
    
            bool askForInput = true;
            while (askForInput)    // same as askForInput == true
            {
                Console.WriteLine("Enter your first number:");
    
                bool conversionOK  = Int32.TryParse(Console.ReadLine(), out a);
    
                if (conversionOK)   // same as conversionOK == true
                {
                    askForInput = false;  // IMPORTANT: this stops the loop
                }
                else
                {
                    Console.WriteLine("Error: Your input was invalid. Please try again.");  // inform the user of the error
                }
            }
    There you go - now just apply that for the other number as well. Know that there are some details to all this that I left out, and that you will eventually learn about (like the do-while version of the loop, and that there are cases where you don't have to use { and }, stuff like that).

    You might be asking why I sometimes used "=" and sometimes "==". This is very important - these are not the same.

    Operator = is used to assign a value to a variable.
    For example, a = 5 puts the number 5 into the memory represented by a.

    Operator == is used to check two values for equality.
    The expression a == 5 does not change the value of a, it checks if a equals to 5. If it does, the whole expression evaluates to true, if not, it evaluates to false. Essentially, it's as if the whole expression is replaced at runtime with a bool value.

    And now, finally, on to the...



    Q2 - How do Repeat the whole process of addition after "thank you" instead of the console screen just disappearing after readkey?

    Use a while loop, in a pretty much the same way you used it in Q1

    Wrap the whole code in Main() in it.
    Code:
    bool exit = false;
    while (!exit)   // the ! is the NOT operator - it inverts the value; read as "while NOT exit"
    {
        // ask the two numbers, add them, show...
        // (omitted)
    
        // now ask the user what to do:
        Console.Write("Again (y/n): ");
        string response = Console.ReadLine();
    
        // We are not going to be to picky - if response == "y", we won't set exit to true,
        // and we'll end the app for any other input.
        // The ToLower() returns a lowercase string, to help us handle if the user inputs "Y".
        if (response.ToLower() != "y")   // != means NOT EQUAL
        {
            exit = true;    // after this, the condition will evaluate to false, and the loop will end
        }
    }

    Q3 - Why do we write write +c (In "the sum=) instead of just a normal C?

    For the same reason you write
    c = a + b

    and not
    c = a b;

    What's going on in
    Console.WriteLine("the sum=" + c)

    is that WriteLine() accepts a string as a parameter.

    The parameter here is:
    "the sum=" + c

    Where "the sum=" is a what's called a string literal, and c is an int variable.
    The number stored in the variable c is silently converted to a string, and then two strings are added together (concatenated).

    So
    "the sum=" + "whatever_was_in_c"

    ends up being
    "the sum=whatever_was_in_c"
    Last edited by TheGreatCthulhu; October 29th, 2012 at 12:38 PM.

  4. #4
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Wow XD
    Such simple questions and yet there's so much to say.

  5. #5
    Join Date
    Oct 2012
    Posts
    4

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Wow! First Of all Thank You Very much for the detailed meticulousness reply and your time. I am so excited!
    However, though you have made every attempt to make the solution simple for me and understandable, i have the following questions against the highlighted text in Blue. (I read and -reread your response. It am sure, i am missing out a whole lot in basic understanding)

    You may please, if you feel, refer me to preliminary reading materials, if you feel, i need to go back to basics again,
    Any which way, Thank you and Kevin much. Really!


    Quote Originally Posted by TheGreatCthulhu View Post
    OK. But first, please use the [code][/code] tags when posting code - this will preserve existing formatting (but it will not format unformulated code). It's important because it's easier for everyone to read and understand, and you're more likely to get help if the code is readable.reful from hereon[/COLOR]

    So, let me take care of that this time:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace AddTwoNumbers
    {
        class Program
        {
            static void Main(string[] args)
            {
                int a,b,c;
    
                Console.WriteLine("Hi! I am here to add two numbers for you!");
                Console.WriteLine("Enter your first number:");
    
                a = Int32.Parse(Console.ReadLine());<----- I re did this as a=Int32(Console.Readline()); without the parse, and i am still able to compute. Why do I need the parse parameter then?
    
                Console.WriteLine("Enter You second Number:");
    
                b = Int32.Parse(Console.ReadLine());
                c = a + b;
    
                Console.WriteLine("the sum=" + c);
                Console.ReadKey();
                Console.WriteLine("thank you!!!");
                Console.ReadKey();
    
            }
        }
    }
    Q1 - How and where do I add an warning of sorts if in case someone inputs a alphabet instead of numbers for the addition?

    It's good that you're thinking about that. In situations like this, you have to make a few decisions about how you want your application to work. Do you exit the app if the user provides invalid input, or do you give him another chance? Do you maybe fallback to a default value if the input is not adequate? How do you inform the user about this?

    Lets assume that the app should work like this:
    1. Ask user to enter a number.
    2. Get input.
    3. If not valid -> show error message, then jump back to (1.)
    4. If valid -> continue on.


    Since you've said that you've just started learning C# (and programming in general) you might not yet be familiar with control flow statements that enable you to do this - but don't worry, it's nothing complicated.

    Let's focus on checking if the input is valid or not first. C# provides what's called a conditional statement, or an if-statement. It looks like this:

    Code:
    if (some_condition)
    {
        // do this if some condition evaluates to true
        // if not, just skip to (the rest of the code)
    }
    
    // (the rest of the code)
    Or like this:

    Code:
    if (some_condition)
    {
        // do this if some condition evaluates to true
    }
    else
    {
        // otherwise do this
    }
    
    // (the rest of the code)
    This can be used to check if the input is valid, and I'll show you how in a moment. But first, take a look at this line:
    a = Int32.Parse(Console.ReadLine());

    What happens here is that Console.ReadLine() gets a string (of characters - i.e. text) from the user, which may or may not be a string representation of a number. That string is then passed to the Int32.Parse() method as a parameter. The line of code above is equivalent to this:
    string input = Console.ReadLine();
    a = Int32.Parse(input);


    The Int32.Parse() method then tries to parse that string, figuring out if it represents a number or not. If it does, it returns that number as an integer (type int, the type of the variable a), a numeric data type your application can work with.
    If it does not it does something you're not familiar with yet - it throws an exception. Exceptions are a part of an error handling mechanism, which causes the application to break out of its normal flow (normal execution stops). Programmers normally write code to handle these exceptions - either by trying to recover, or by gracefully informing the user about the error and terminating the app, depending on the situation.
    However, that's not what you're going to do now - you'll do that once you learn more about C#.
    For now, I'm gonna tell you that there's another variant of the Int32.Parse() method called Int32.TryParse(), which does not throw an exception, but returns a Boolean value which indicates if the conversion was successful or not.
    Boolean type variables (type bool) can have only two values - true or false, as you might already know. These can be used as the conditions in an if-statement.

    Now, TryParse() is used a bit differently than Parse():


    string input = Console.ReadLine();
    int number;
    bool conversionOK = Int32.TryParse(input, out number); <----- Why does one write Conversionok. Is it a predetermined command? I couldn't find anything in google.

    // after the previous line, number should contain the value provided by the user


    Basically, the TryParse() function now doesn't return the number, but it returns the success indicator. Instead of doing it the standard way, it uses an output parameter (note the out keyword) to "return" the number in a different way. You'll learn about output parameters later on.

    What's important to know is that now you can do this:
    Code:
                Console.WriteLine("Hi! I am here to add two numbers for you!");
                Console.WriteLine("Enter your first number:");
    
                bool conversionOK  = Int32.TryParse(Console.ReadLine(), out a);
    
                if (conversionOK == false)
                {
                    Console.WriteLine("Error: Your input was invalid.");  // inform the user of the error
                }
    Now onto the second part - how to repeat the process in the case of error. Well, meet the while-loop.
    Code:
    while (some_contition)
    {
        // repeat this code block as long as some_contition evaluates to true 
        // Note1: if some_contition == false to begin with, this block never executes
        // If some_contition is true, and it never becomes false, this loop will run forever! Not good!
    }
    So, all you need to do is create a bool variable to be used as the condition of the while-loop, and modify it to indicate if the program should ask for the input again or not. Like this:
    [CODE]
    Console.WriteLine("Hi! I am here to add two numbers for you!");

    bool = true;<------- What does askForInput mean? Input could be a number or an alphabet? How does the code know whether it is true or not, unless we define what 'true' in this scenario means. Also shouldn't code stop if conversionok is false.

    I mean this is how i understood this
    While parameter will run if some conditions are met (like you explained)

    So when askforinput = true
    It runs
    [code]Console.WriteLine("Enter your first number:");

    bool conversionOK = Int32.TryParse(Console.ReadLine(), out a);

    if (conversionOK) // same as conversionOK == true
    Code:
     But if ConversionOk is true it falsifies the while parameter and moves to the second number
    Else it will display Error: Your input was Invalid message.
    
    Is this understanding correct?
    Code:
    
            while (askForInput)    // same as askForInput == true
            {
                Console.WriteLine("Enter your first number:");
    
                bool conversionOK  = Int32.TryParse(Console.ReadLine(), out a);
    
                if (conversionOK)   // same as conversionOK == true
                {
                    askForInput = false;  // IMPORTANT: this stops the loop
                }
                else
                {
                    Console.WriteLine("Error: Your input was invalid. Please try again.");  // inform the user of the error
                }
            }
    There you go - now just apply that for the other number as well. Know that there are some details to all this that I left out, and that you will eventually learn about (like the do-while version of the loop, and that there are cases where you don't have to use { and }, stuff like that).

    You might be asking why I sometimes used "=" and sometimes "==". This is very important - these are not the same.

    Operator = is used to assign a value to a variable.
    For example, a = 5 puts the number 5 into the memory represented by a.

    Operator == is used to check two values for equality.
    The expression a == 5 does not change the value of a, it checks if a equals to 5. If it does, the whole expression evaluates to true, if not, it evaluates to false. Essentially, it's as if the whole expression is replaced at runtime with a bool value.

    And now, finally, on to the...



    Q2 - How do Repeat the whole process of addition after "thank you" instead of the console screen just disappearing after readkey?

    Use a while loop, in a pretty much the same way you used it in Q1

    Wrap the whole code in Main() in it.
    Code:
    bool exit = false;<--- what does this mean? Didn't understand the exit part.
    while (!exit)   // the ! is the NOT operator - it inverts the value; read as "while NOT exit"
    {
        // ask the two numbers, add them, show...
        // (omitted)
    
        // now ask the user what to do:
        Console.Write("Again (y/n): ");
        string response = Console.ReadLine();
    
        // We are not going to be to picky - if response == "y", we won't set exit to true,
        // and we'll end the app for any other input.
        // The ToLower() returns a lowercase string, to help us handle if the user inputs "Y".
        if (response.ToLower() != "y")   // != means NOT EQUAL
        {
            exit = true;    // after this, the condition will evaluate to false, and the loop will end
        }
    }

    Q3 - Why do we write write +c (In "the sum=) instead of just a normal C?

    For the same reason you write
    c = a + b

    and not
    c = a b;

    What's going on in
    Console.WriteLine("the sum=" + c)

    is that WriteLine() accepts a string as a parameter.

    The parameter here is:
    "the sum=" + c

    Where "the sum=" is a what's called a string literal, and c is an int variable.
    The number stored in the variable c is silently converted to a string, and then two strings are added together (concatenated).

    So
    "the sum=" + "whatever_was_in_c"

    ends up being
    "the sum=whatever_was_in_c"

  6. #6
    Join Date
    Oct 2012
    Posts
    4

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Console.WriteLine("Hi! I am here to add two numbers for you!");

    bool askforinput = true;<------- What does askForInput mean? Input could be a number or an alphabet? How does the code know whether it is true or not, unless we define what 'true' in this scenario means. Also shouldn't code stop if conversionok is false.

    I mean this is how i understood this
    While parameter will run if some conditions are met (like you explained)

    So when askforinput = true
    It runs
    [CODE]Console.WriteLine("Enter your first number:");

    bool conversionOK = Int32.TryParse(Console.ReadLine(), out a);

    if (conversionOK) // same as conversionOK == true [CODE]

    But if ConversionOk is true it falsifies the while parameter and moves to the second number
    Else it will display Error: Your input was Invalid message.

    Is this understanding correct?

  7. #7
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Quote Originally Posted by Dawnz
    a = Int32.Parse(Console.ReadLine());<----- I re did this as a=Int32(Console.Readline()); without the parse, and i am still able to compute. Why do I need the parse parameter then?
    That should not be possible - are you sure this is the case? It shouldn't compile. Double check. Maybe you somehow accidentally added a method called Int32? Does the program crash when you run it?
    If you can't figure it out, past in all of your current code.

    Quote Originally Posted by Dawnz
    bool conversionOK = Int32.TryParse(input, out number); <----- Why does one write Conversionok. Is it a predetermined command? I couldn't find anything in google.
    No - it's just a name I gave to the variable; you can give it any name you like, but, it's a good practice to give it some name that tells you what it is used for, or what it represents. This way you and other people will be able to understand your code better. Also, sometimes, when you come back after some time to an old program after working on something else, variables with informative names are of great help when you want to pick up where you left off.

    Also, when you use a conditional statement with such a variable, it almost feels like English:
    if (conversionOK)

    Writing that is better that:
    if (cvtd) // where cvtd would stand for "converted [succesfully]"

    Quote Originally Posted by Dawnz
    bool askForInput = true; <------- What does askForInput mean? Input could be a number or an alphabet? How does the code know whether it is true or not, unless we define what 'true' in this scenario means.
    Again, askForInput is just a name I chose for the variable - it can really be named anything. You could rename it to askForInputAgain. It's just a true/false variable used as an indicator of whether the program should continue to ask for the same input or not, in case the user didn't enter an integer value.

    For the same reason the next line is almost self explanatory:
    while(askForInput)

    Or It could have been:
    while(askForInputAgain)


    Rather than:
    while(takeIpt)

    It is initially set to true so that the code inside the while-loop will execute at least once. Then inside the loop, a check is made using an if-statement to determine if the input was valid or not. The code (or the program) itself doesn't "know" anything - you as the programmer have to tell it. This is why, when the if-statement determines that the input was indeed valid, it sets the askForInput variable to false. This doesn't break the loop immediately, instead, the code continues on till the end of the block (between "{" and "}"), but I arranged it so that nothing more is executed once valid input was received. The execution flow then loops back to the beginning, onto the next iteration, and at that point the loop's condition is re-checked. Since now askForInput == false (there's no more reason to ask for the same input again), the while loop ends, and the whole while-block is skipped, and the execution continues after the "}" - so the program asks the user to input the value for the next variable.

    Quote Originally Posted by Dawnz
    Also shouldn't code stop if conversionok is false.
    No. Not automatically.

    In this case, i haven't yet introduced the while loop:
    Code:
    if (conversionOK == false)
    {
        Console.WriteLine("Error: Your input was invalid.");  // inform the user of the error
    }
    This was just to show you how to figure out if the input was valid or not.
    The value of conversionOK was set by the call to TryParse() before.
    If conversionOK is false, the expression (conversionOK == false) evaluates to true (because what's it then becomes (false == false), which is correct, that is, true.). So if conversionOK is false, the condition is satisfied, so the error message is displayed. After that, the execution continues to the first line after the end of the if-block "}". If the input was valid and conversionOK is true, then the condition is not satisfied, and the code inside if is not executed - the program simply skips it and continues after the "}".


    In the other case, I factored in the while loop, and I modified the code a bit:
    Code:
    if (conversionOK)   // same as conversionOK == true
    {
        // IMPORTANT: this stops the while loop (not instantly! - it happens on the next reevaluation of the condition specified for the while loop)
        askForInput = false;  
    }
    else
    {
        Console.WriteLine("Error: Your input was invalid. Please try again.");  // inform the user of the error
    }
    Now the condition is for conversionOK to be true, if it is, the first part will be executed, the "else"-part will be skipped, and the app will continue after the last "}" here. If conversionOK turns out to be false, the "else"-part will be executed, followed by the rest of the code.

    Quote Originally Posted by Dawnz
    I mean this is how i understood this
    While parameter will run if some conditions are met (like you explained)

    So when askforinput = true
    It runs
    Yes.

    Quote Originally Posted by Dawnz
    But if ConversionOk is true it falsifies the while parameter and moves to the second number
    Else it will display Error: Your input was Invalid message.

    Is this understanding correct?
    Yes. But, just in case, I want to clarify that it is the code in the if statement that falsifies askForInput. The two variables (askForInput and conversionOK) are not implicitly interrelated. Changing one doesn't affect the other unless you specify that this should happen at some point in time during the execution of your program. I already explained the details of how the while loop actually stops.


    Quote Originally Posted by Dawnz
    bool exit = false;<--- what does this mean? Didn't understand the exit part.
    while (!exit) // the ! is the NOT operator - it inverts the value; read as "while NOT exit"
    Again, exit is just a name I gave to that variable. Could have been called "quit", or "q" (not recommended), or something else.
    The idea is that that is a bool indicator of whether the application should end and exit or not. Initially, it is set to false (which means I don't want the app to exit just jet - I want it to run it's addition logic at least once). Then the while loop's condition demands for exit to be false. It's the same as while (exit == false). It then executes whatever is inside the loop's body (the {} block). Inside the body of this while loop, at the very end, the user is asked to answer if the app should do it's thing again or not. If the user enters anything other that "y", the exit variable is set to true, to indicate that the app should finish. Before attempting another iteration, the while loop checks it's condition, sees that it is not satisfied any longer (exit is no longer false), so it skips everything inside it, and the execution continues outside the while body. As there is no more code there, the Main() function ends, and thus, the program exits.

    P.S. These things will become clear as you code more and more. Any introductory text or tutorial is bound to cover this stuff, so just keep going.

    P.P.S. Note that C# is a case sensitive language; it treats conversionOK, ConversionOk, conversionok, etc.., as different names.
    Last edited by TheGreatCthulhu; October 29th, 2012 at 05:30 PM.

  8. #8
    Join Date
    Oct 2012
    Posts
    4

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Hi Cthulhu!


    I am reading your responses again in its entirety for better understanding. I did check, and the program runs even when i do not use Int32.parse ( So i think! ). I am attaching a screen shot and here is the code.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    
    namespace ConsoleApplication5
    {
        class Program
        {
            static void Main(string[] args)
            {
                int a,b,c;
    
                Console.WriteLine("Hi! I  am here to add two numbers for you!");
                Console.WriteLine("Enter your first number:");
               
             
    
                  a = Int32(Console.ReadLine());
                   Console.WriteLine("Enter You second Number:");
                              
                b = Int32(Console.ReadLine());
                c = a + b;
                Console.WriteLine("the sum="+c);
                Console.ReadKey();
                Console.WriteLine("thank you!!!");
                Console.ReadKey();
    
            }
        }
    }
    Name:  int32.jpg
Views: 1749
Size:  53.7 KB

    Thanks again for your response. I am going to work on it tonite and see if i can get somewhere with understanding it better.

    regards,

    Quote Originally Posted by TheGreatCthulhu View Post
    That should not be possible - are you sure this is the case? It shouldn't compile. Double check. Maybe you somehow accidentally added a method called Int32? Does the program crash when you run it?
    If you can't figure it out, past in all of your current code.


    No - it's just a name I gave to the variable; you can give it any name you like, but, it's a good practice to give it some name that tells you what it is used for, or what it represents. This way you and other people will be able to understand your code better. Also, sometimes, when you come back after some time to an old program after working on something else, variables with informative names are of great help when you want to pick up where you left off.

    Also, when you use a conditional statement with such a variable, it almost feels like English:
    if (conversionOK)

    Writing that is better that:
    if (cvtd) // where cvtd would stand for "converted [succesfully]"



    Again, askForInput is just a name I chose for the variable - it can really be named anything. You could rename it to askForInputAgain. It's just a true/false variable used as an indicator of whether the program should continue to ask for the same input or not, in case the user didn't enter an integer value.

    For the same reason the next line is almost self explanatory:
    while(askForInput)

    Or It could have been:
    while(askForInputAgain)


    Rather than:
    while(takeIpt)

    It is initially set to true so that the code inside the while-loop will execute at least once. Then inside the loop, a check is made using an if-statement to determine if the input was valid or not. The code (or the program) itself doesn't "know" anything - you as the programmer have to tell it. This is why, when the if-statement determines that the input was indeed valid, it sets the askForInput variable to false. This doesn't break the loop immediately, instead, the code continues on till the end of the block (between "{" and "}"), but I arranged it so that nothing more is executed once valid input was received. The execution flow then loops back to the beginning, onto the next iteration, and at that point the loop's condition is re-checked. Since now askForInput == false (there's no more reason to ask for the same input again), the while loop ends, and the whole while-block is skipped, and the execution continues after the "}" - so the program asks the user to input the value for the next variable.


    No. Not automatically.

    In this case, i haven't yet introduced the while loop:
    Code:
    if (conversionOK == false)
    {
        Console.WriteLine("Error: Your input was invalid.");  // inform the user of the error
    }
    This was just to show you how to figure out if the input was valid or not.
    The value of conversionOK was set by the call to TryParse() before.
    If conversionOK is false, the expression (conversionOK == false) evaluates to true (because what's it then becomes (false == false), which is correct, that is, true.). So if conversionOK is false, the condition is satisfied, so the error message is displayed. After that, the execution continues to the first line after the end of the if-block "}". If the input was valid and conversionOK is true, then the condition is not satisfied, and the code inside if is not executed - the program simply skips it and continues after the "}".


    In the other case, I factored in the while loop, and I modified the code a bit:
    Code:
    if (conversionOK)   // same as conversionOK == true
    {
        // IMPORTANT: this stops the while loop (not instantly! - it happens on the next reevaluation of the condition specified for the while loop)
        askForInput = false;  
    }
    else
    {
        Console.WriteLine("Error: Your input was invalid. Please try again.");  // inform the user of the error
    }
    Now the condition is for conversionOK to be true, if it is, the first part will be executed, the "else"-part will be skipped, and the app will continue after the last "}" here. If conversionOK turns out to be false, the "else"-part will be executed, followed by the rest of the code.



    Yes.


    Yes. But, just in case, I want to clarify that it is the code in the if statement that falsifies askForInput. The two variables (askForInput and conversionOK) are not implicitly interrelated. Changing one doesn't affect the other unless you specify that this should happen at some point in time during the execution of your program. I already explained the details of how the while loop actually stops.




    Again, exit is just a name I gave to that variable. Could have been called "quit", or "q" (not recommended), or something else.
    The idea is that that is a bool indicator of whether the application should end and exit or not. Initially, it is set to false (which means I don't want the app to exit just jet - I want it to run it's addition logic at least once). Then the while loop's condition demands for exit to be false. It's the same as while (exit == false). It then executes whatever is inside the loop's body (the {} block). Inside the body of this while loop, at the very end, the user is asked to answer if the app should do it's thing again or not. If the user enters anything other that "y", the exit variable is set to true, to indicate that the app should finish. Before attempting another iteration, the while loop checks it's condition, sees that it is not satisfied any longer (exit is no longer false), so it skips everything inside it, and the execution continues outside the while body. As there is no more code there, the Main() function ends, and thus, the program exits.

    P.S. These things will become clear as you code more and more. Any introductory text or tutorial is bound to cover this stuff, so just keep going.

    P.P.S. Note that C# is a case sensitive language; it treats conversionOK, ConversionOk, conversionok, etc.., as different names.

  9. #9
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Addition of Two Numbers: How to Warn user to not to use alphabets as input?

    Quote Originally Posted by Dawnz View Post
    I did check, and the program runs even when i do not use Int32.parse ( So i think! ). I am attaching a screen shot and here is the code.
    No it doesn't (). Good thing for the screenshot, or I'd be truly baffled.
    See that blue squiggly line under the occurrences of Int32 in your screenshot? Those indicate places that cause compilation errors. Your program doesn't compile! What you are running over there must be some previously compiled version of the program - from before you changed the source code (for the changes to the src code to take effect, you must recompile every time).

    If you hit F5, the error messages should appear at the bottom of the IDE, and a window should pop up saying "There were build errors. Would you like to continue and run the last successful build?".
    You didn't just click Yes on that, without reading it?

    The console application you're seeing is not made from your current source code. You must correct the errors first.
    Last edited by TheGreatCthulhu; October 29th, 2012 at 06:25 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured