Answered Why is my field not working?

WB1975

Well-known member
Joined
Apr 3, 2020
Messages
87
Programming Experience
Beginner
Hello guys,

cant remember if really newb questions go here.

anyway, i am writing a basic times table program

asks the user for number between 1 and 12 then spits out that numbers times table, but im having a problem, why cant number be carried through the do while loop?
i would have thought that public int number would be readable throughout the program?
my last line Console.WriteLine(number); , number is just not avilable.

C#:
using System;

namespace MuliplicationTable
{

    class Program
    {
        public int number;

        static void Main(string[] args)
        {
            Console.WriteLine("Multiplication Tables");
            Console.WriteLine("*********************");

            bool hasValidNumber = false;

            do
            {
                Console.WriteLine("Enter number between 1 and 12:");
                int number = Console.Read();
                if (number > 1 && number < 12)
                {
                    hasValidNumber = true;
                } else
                {
                    hasValidNumber = false;
                }
            } while (!hasValidNumber);

            Console.WriteLine(number);
        }
    }
}
 
You have two variables named number in that code, one declared in class (a field) and one declared inside the do loop (a local variable). Outside the do block you are using the field.
 
You have two variables named number in that code, one declared in class (a field) and one declared inside the do loop (a local variable). Outside the do block you are using the field.

but why cant i print out number? its just underlined in red in this line:
Console.WriteLine(number);
 
Does Visual Studio by any chance give you this error message?
An object reference is required for the non-static field, method, or property 'Program.number'
This is something you have to explain when posting in forums. You can't expect anyone to replicate your code or guess it.

Hint: Main method is static, while the class variable is an instance field of the Program class.
 
ok will do in future john

ok so i made the variable

public static int userVariable;

so in order for the variable to be used without the static keyword you would need to make an object from the class which is not required for this small program.

but how do i assign the local value to the global value? isnt that what the this keyword is for? but it doesnt work.

thanks
 
Last edited:
how do i assign the local value to the global value?
Don't declare a local variable in the first place. That way, the only variable to consider is the member. You obviously know how to assign a value to a variable because you're doing it in your code, e.g.
C#:
hasValidNumber = true;
Why are you insisting on something different here:
C#:
int number = Console.Read();
isnt that what the this keyword is for? but it doesnt work.
this is to specify a member of the current object but your code is in a static method so there is no current object. That's why you needed to declare the field static too. The Main method is always static so you cannot access instance members from within it. If you create an object of any type then that is an instance, so you can access instance members of that object.
 
The field isn't used outside the method, so just declare and use a local variable inside the method.
 
Thanks guys got it working perfectly.

is there anything that should be changed?

C#:
using System;


namespace MuliplicationTable
{

    class Program
    {
        public static int userNumber;

        static void Main(string[] args)
        {
            bool hasValidNumber = false;
            while (!hasValidNumber)
            {
                Console.WriteLine("Enter number between 1 and 12:");

                userNumber = Convert.ToInt32(Console.ReadLine());

                if (userNumber >= 1 && userNumber <= 12)
                {
                    hasValidNumber = true;
                }
                else
                {
                    Console.WriteLine("That is not a valid number between 1 and 12:");
                }
            }
            
            for (int i=1;i <= 12;i++)
            {
                Console.WriteLine(i + " X " + userNumber + " = " + (i * userNumber));
            }
        }
    }
}
 
Someone's going to be mighty confused when they come back. :LOL::LOL:
Fair point. To clarify, the issue is that you were using two variables with the same name at different scopes. You should just be using one of those variables. It is preferable to use a local variable if that is all you need. If you need a variable that retains its value when a local would fall out of scope, use a member instead.
 
is there anything that should be changed?
Just stylistic things...
C#:
using System;

namespace MuliplicationTable
{
    class Program
    {
        const int InputMin = 1;
        const int InputMax = 12;
        const int MultiplierMin = 1;
        const int MultiplierMax = 12;

        static void Main(string[] args)
        {
            int userNumber;
            bool hasValidNumber = false;

            do
            {
                Console.Write($"Enter number between {InputMin} and {InputMax}: ");
                
                string input = Console.ReadLine();
                hasValidNumber = int.TryParse(input, out userNumber);
                hasValidNumber = hasValidNumber && InputMin <= userNumber && userNumber <= InputMax;
                if (!hasValidNumber)
                {
                    Console.WriteLine("That is not a valid number between {InputMin} and {InputMax}.");
                }
            } while (!hasValidNumber);

            for (int i = MultiplierMin; i <= MultiplierMax; i++)
            {
                Console.WriteLine($"{i} X {userNumber} = {i * userNumber}"");
                // or
                // Console.WriteLine("{0} X {1} = {2}", i, userNumber, i * userNumber)
            }
        }
    }
}

or

C#:
using System;

namespace MuliplicationTable
{
    class Program
    {
        static int GetInteger(int min, int max)
        {
            while (true)
            {
                Console.Write($"Enter number between {min} and {max}: ");

                string input = Console.ReadLine();
                if (int.TryParse(input, out int value) &&
                    min <= value && value <= max)
                {
                    return value;
                }
                
                Console.WriteLine($"That is not a valid number between {min} and {max}.");
            }
        }
        
        static void ShowMultiplicationValues(int multiplicand, int multiplierMin, int multiplierMax)
        {
            for (int i = multiplierMin; i <= multiplierMax; i++)
            {
                Console.WriteLine($"{i} X {multiplicand} = {i * multiplicand}"");
            }
        }
                                  
        const int InputMin = 1;
        const int InputMax = 12;
        const int MultiplierMin = 1;
        const int MultiplierMax = 12;

        static void Main(string[] args)
        {
            int multiplicand = GetInteger(InputMin, InputMax);
            ShowMultiplicationValues(multiplicand, MultiplierMin, MultiplierMax);
        }
    }
}
 
Back
Top Bottom