Hello there folks. I'm very new to programming and am having a bit of trouble with one of my first projects, a simple "lottery number generator" programme.

At first, it all appeared to be fine, but of course a lottery number generator cannot generate two identical numbers in a single selection!

So I need to implement some sort of 'check and reassign if neccesary' routines in order to prevent this. I thought that it would be easiest to have each number sequence selected as an array, and then check against the other members of the array with stacked 'for' statements.

But before I can get to this point, myy problem is that I want to have a constructor with one parameter to set the number of 'balls' each lottery selection will have. I think I'm having some trouble with the basics of declaring arrays. Here's my code:

// Lottery numbers selector
// --------------------------

using System;

public class lottery
	public int[] nbrs;
	public lottery(int balls)
		int[] nbrs = new int[balls];
public class lottoapp
	public static void Main()
		Console.WriteLine("In main...");
		Console.WriteLine("Instantiating a 6-ball lottery...");
		lottery lotto = new lottery(6);
		Console.WriteLine("Setting number of balls...");
		Console.WriteLine("Printing number of balls...");
		Console.WriteLine("Number of balls = {0}", lotto.nbrs.Length);

It compiles, but I get the following error:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at lottoapp.Main() in c:\documents\lottery.cs line 23

Line 23 is the final line, and I figured that seeing as I'd instantiated 'lotto' as an object of the class 'lottery', that lotto.nbr.Length would get me the Length member of the array.

So please, any tips on what I'm doing wrong here?

Edited by Lebowsk1: n/a

8 Years
Discussion Span
Last Post by Narue

>int[] nbrs = new int[balls];
This (line 11) declares a local variable in your constructor that hides the class field. You initialize the local array, but the class field remains null. Change it to this:

nbrs = new int[balls];
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.