0

When I run this console app, everything works fine but except for my UserAnswer() result. It keeps returning a value of '0' for both num1 & num2. This doesn't make sense to me because I don't receive any errors for declaring a new value for num1 & num2 in Input1() & Input2() methods. It compiles and runs fine but why is it not picking up the new values of these variables?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

 namespace CalculatorApp
{
    public class Program
    {
        float Number;
        float num2;
        float num1;
        public static void Main(string[] args)
        {
            // Display title as the C# console calculator app.

            Console.WriteLine("Console Calculator in C#\r");
            Console.WriteLine("------------------------\n");
            //Console.ReadKey();

            // execute program functions
            new Program().Input1();
            new Program().Input2();
            new Program().UserOption();
            new Program().UserAnswer();
            new Program().PromptUserExit();
        }
            // Ask the user to type the first number.
            //Console.WriteLine("Type a number, and then press Enter");

        public float Input1() {
            Console.WriteLine("Type a number, and then press Enter");
            bool Valid = false;
            while (Valid == false)
            {
                string Input = Console.ReadLine();
                if (!float.TryParse(Input, out Number))
                {
                    Console.WriteLine("Not an integer, please try again.");
                }
                else
                {
                    Valid = true;
                    num1 = (float)Convert.ToDecimal(Input);
                } 
            } return num1;
}
        public float Input2() {
            // Ask the user to type the second number.
            Console.WriteLine("Type another number, and then press Enter");
            bool Valid2 = false;
            while (Valid2 == false)
            {
                string Input2 = Console.ReadLine();
                if (!float.TryParse(Input2, out Number))
                {
                    Console.WriteLine("Not an integer, please try again.");

                }
                else
                {
                    Valid2 = true;
                    num2 = (float)Convert.ToDecimal(Input2);
                }
            } return num2;
        }

        public void UserOption() {
            // Ask the user to choose an option.
            Console.WriteLine("Choose an option from the following list:");
            Console.WriteLine("\ta - Add");
            Console.WriteLine("\ts - Subtract");
            Console.WriteLine("\tm - Multiply");
            Console.WriteLine("\td - Divide");
            Console.Write("Your option? ");
        }

        public void UserAnswer() {
            bool isOperatorValid;
            do
            {
                isOperatorValid = true;
                switch (Console.ReadLine())
                {
                    case "a":
                        Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
                        break;
                    case "s":
                        Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
                        break;
                    case "m":
                        Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
                        break;
                    case "d":
                        Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                        break;
                    default:
                        Console.WriteLine("Invalid input please try again");
                        isOperatorValid = false;
                        break;
                }
            } while (!isOperatorValid);
        }
        public void PromptUserExit() { 
            // Wait for the user to respond before closing.
            Console.Write("Press any key to close the Calculator console app...");
                Console.ReadKey();
            }
        }
    }
2
  • There is a lot of stuff that is going on here, but !float.TryParse(...) already converts it, why are you using Convert.ToDecimal(...)? Just return Number; in the else. You also should make the functions static, so you don't have to do new Program.(...) which is a really odd syntax. Commented Dec 30, 2019 at 20:55
  • 2
    Every time you do new Program you create a new object of class program with its own variables num1 num2 etc Commented Dec 30, 2019 at 20:58

1 Answer 1

4

This is your problem:

new Program()

You are creating a new instance of the Program class every time you call a method. Each time, the variables are initialized with the default value of 0.

You need to initialize the class once, then use the same class:

var program = new Program();
program.Input1();
program.Input2();
program.UserOption();
program.UserAnswer();
program.PromptUserExit();

Or you could just make all of your methods and variables static so that you can call them directly without initializing a new object. In bigger programs, you would want to be careful with declaring things static (there is a time and place, but it's not "always"). But in a small program like this, it's fine.

Sign up to request clarification or add additional context in comments.

5 Comments

It's still really strange syntax, all the methods/fields should be static instead, and just call them directly instead of creating a new Program class.
oh i see! thank you! will try this. wait but how do you make variables static? or is that just comes with declaring methods static?
@RonBeyer True, that's another way too. I updated my answer. It's only an odd syntax only because it's the root class of the program. It would be more "normal" if it was a totally different class like MyCalculator, since that would isolate that logic into a specific class. But then it would only make sense to do that if you had other classes for other pieces of the program. In such a small program, it's not really that important.
@testingTester You just put the word static in the declaration. You can read the documentation on the static modifier here to understand what it does: learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
thank you Gabriel! this helped a lot! very new to programming so not being familiar with all of the tools available & their functionality kinda sucks. appreciate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.