C# 语言 |初始化数组给出 System.NullReferenceException

C# | Initialized array gives System.NullReferenceException

提问人:cloudified 提问时间:3/2/2022 最后编辑:cloudified 更新时间:3/2/2022 访问量:97

问:

我目前正在用 C# 制作一个彩票模拟器,但现在我想制作一个功能来让用户随机化他们的彩票号码,而不必使用数组手动编写它们,但它给了我错误代码:

引发异常 System.NullReferenceException:“对象引用未设置为对象的实例。

我为随机数声明并初始化了名为“randomList”的数组,如下所示:

public static int[] randomList = new int[5];

在我想编写存储用户在数组中得到的 6 个随机数的代码之后:

Console.WriteLine("\nRandomized 6 numbers: ");
for (int z = 0; z <= 6; z++)
{
  int rndNum = rnd.Next(1, 50);
  randomList[z] = rndNum;               // <-- ERROR 
  Console.Write(rndNum + ", ");
}

我以为只有在您没有初始化变量或数组的情况下才会收到该错误。我希望有人向我解释错误以及如何避免/修复它!谢谢!

在这里,您可以访问整个代码(第 203 行中的错误):

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

namespace Lottery
{
    internal class Program
    {
        // Global Variables:

        // Playing
        public static int playoption;
        public static int betoption;
        public static int gameAmount;
        public static int gameCost = 10;
        public static int superNumCost = 5;
        public static string includeSuperNum;
        public static int tickets;
        public static int superNumTickets;
        // Used for the Lotto Numbers
        public static int[] correctList = new int[5];
        public static int[] randomList = new int[5];
        public static int[] manualList = new int[5];
        // Indicators if you have correct numbers
        public static int userCorrect;
        public static int userSuperCorrect;

        // Bank
        public static int bankoption;
        public static int deposit;
        public static int withdrawal;
        public static int balance = 0;
        public static int cash = 300;

        static void Main()
        {
            // Variables

            // Menu
            int menuoption;

            Console.Clear();
            Console.WriteLine("=== LOTTO! 6 out of 49 ===");
            Console.WriteLine(" 1. Play");
            Console.WriteLine(" 2. Bank Menu");
            Console.WriteLine(" 3. Go work");
            Console.WriteLine(" 4. Quit");
        WrongMenu:
            Console.Write("\nEnter your option by typing out the number: ");
            menuoption = Convert.ToInt32(Console.ReadLine());
            switch (menuoption)
            {
                case 1:
                    PlayMenu();
                    break;
                case 2:
                    Bank();
                    break;
                case 3:
                    Work();
                    break;
                case 4:
                    break;
                default:
                    Console.WriteLine("Invalid option - Enter your option again: ");
                    goto WrongMenu;
            }



        }
        // All code for playing Lotto:
        static void PlayMenu()
        {
            Console.Clear();
            Console.WriteLine("=== PLAY MENU ===");
            Console.WriteLine(" 1. Buy Tickets");
            Console.WriteLine(" 2. Check Tickets");
            Console.WriteLine(" 3. Back to Main Menu");
        WrongPlayMenu:
            Console.Write("\nEnter your option to continue: ");
            playoption = Convert.ToInt32(Console.ReadLine());

            switch (playoption)
            {
                case 1:
                    Console.Clear();
                    Console.WriteLine("=== PRIZES ===");
                    Console.WriteLine(" Lottery ticket = " + gameCost + " Euro");
                    Console.WriteLine(" Super Number Addon = " + superNumCost + " Euro");
                    Console.Write("\nHow many lottery tickets do you want to buy?: ");
                    gameAmount = Convert.ToInt32(Console.ReadLine());
                    if ((gameCost * gameAmount) <= cash)
                    {
                        cash = cash - (gameCost * gameAmount);
                        Console.WriteLine("Successfully bought " + gameAmount + " lottery tickets!");
                        if (cash - (gameAmount * superNumCost) >= 0)
                        {
                            Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
                            includeSuperNum = Console.ReadLine();
                            while (includeSuperNum != "Y" && includeSuperNum != "N")
                            {
                                Console.WriteLine("Invalid answer - Type in your answer again only using Y for Yes or N for No.");
                                Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
                                includeSuperNum = Console.ReadLine();
                            }
                            if (includeSuperNum == "Y")
                            {
                                cash = cash - (gameAmount * superNumCost);
                                superNumTickets += gameAmount;
                                Console.WriteLine("Successfully bought Super Number Addon for your ticket/s!");
                            }
                            else
                            {
                                tickets = tickets + gameAmount;
                                Console.WriteLine("No Super Number Tickets bought - Transaction done");
                            }
                        }
                    }
                    Console.WriteLine("\nPress any key to go back to Play Menu");
                    Console.ReadKey();
                    PlayMenu();
                    break;
                case 2:
                    Console.Clear();
                    if (tickets == 0 && superNumTickets == 0)
                    {
                        Console.WriteLine("You have no tickets - Go buy some!");
                        Console.WriteLine("Press any key to go back to Play Menu");
                        Console.ReadKey();
                        PlayMenu();

                    }
                    if (tickets >= 1)
                    {
                        Console.WriteLine("\nYou have " + tickets + " normal tickets");

                    }
                    if (superNumTickets >= 1)
                    {
                        Console.WriteLine("You have " + superNumTickets + " tickets with the Super Number Addon.\n");
                    }
                    Console.WriteLine("=== BETTING ON TICKETS ===");
                    Console.WriteLine(" 1. Bet on normal tickets");
                    Console.WriteLine(" 2. Bet on Super Number tickets");
                    Console.WriteLine(" 3. Back to Play Menu");
                BetWrong:
                    Console.Write("\nEnter your option by typing out the number: ");
                    betoption = Convert.ToInt32(Console.ReadLine());

                    switch (betoption)
                    {
                        case 1:
                            Bet();
                            break;
                        case 2:
                            SuperBet();
                            break;
                        case 3:
                            PlayMenu();
                            break;
                        default:
                            Console.WriteLine("Invalid answer - Try typing it again.");
                            goto BetWrong;
                    }
                    break;
                case 3:
                    Main();
                    break;
                default:
                    Console.WriteLine("Invalid answer - Try typing it again.");
                    goto WrongPlayMenu;

            }
        }
        static void Bet()
        {
            Console.WriteLine("Your tickets:\n");
            for (int x = 1; x <= tickets; x++)
            {
                Console.WriteLine("  Normal ticket Nr. " + x);
            }
            Console.Write("\nEnter the ticket number to bet on it: ");
            int ticketNum = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nSuccessfully opened ticket Nr. " + ticketNum);
        WrongRandomOption:
            Console.Write("Do you want to randomize your 6 Numbers or write them out? Enter 1 for random or 2 for manual: ");
            int chooseIfRandom = Convert.ToInt32(Console.ReadLine());
            Random rnd = new Random();

            switch (chooseIfRandom)
            {
                case 1:

                    Console.WriteLine("\nRandomized 6 numbers: ");
                    for (int z = 0; z <= 5; z++)
                    {
                        int rndNum = rnd.Next(1, 50);
                        randomList[z] = rndNum;
                        Console.Write(rndNum + ", ");
                    }
                    Console.WriteLine("\nThe correct Numbers are: ");
                    for (int c = 1; c <= 5; c++)
                    {
                        int correctNum = rnd.Next(1, 50);
                        correctList[c] = correctNum;
                        Console.Write(correctNum + ", ");
                    }
                    for (int h = 0; h <= 6; h++)
                    {
                        if (randomList[h] == correctList[h])
                        {
                            userCorrect++;
                        }
                    }
                    Console.WriteLine("You got " + userCorrect + " correct Numbers");
                    switch (userCorrect)
                    {
                        case 1:
                            Console.WriteLine("You won 3 Euros!");
                            cash += 3;
                            break;
                        case 2:
                            Console.WriteLine("Nice! You won 7 Euros!");
                            cash += 7;
                            break;
                        case 3:
                            Console.WriteLine("Wow! You won 12 Euros!");
                            cash += 12;
                            break;
                        case 4:
                            Console.WriteLine("Amazing! You won 50 Euros!");
                            cash += 50;
                            break;
                        case 5:
                            Console.WriteLine("Incredible! You won 4.200 Euros!");
                            cash += 4200;
                            break;
                        case 6:
                            Console.WriteLine("JACKPOT! You won 830.000 Euros!");
                            cash += 830000;
                            break;
                    }
                    userCorrect = 0;
                    break;

                case 2:
                    for (int m = 0; m <= 6; m++)
                    {
                    ManualWrong:
                        Console.WriteLine("Enter your " + (m + 1) + ". number: ");
                        manualList[m] = Convert.ToInt32(Console.ReadLine());
                        if (manualList[m] >= 50 || manualList[m] < 1)
                        {
                            Console.WriteLine("Entered number is either too high or low - Enter again (Between 1 and 49)\n");
                            goto ManualWrong;
                        }
                    }
                    Console.WriteLine("\nYour numbers are: ");
                    for (int k = 0; k <= 6; k++)
                    {
                        Console.Write(manualList[k] + ", ");
                    }
                    Console.WriteLine("\nThe correct Numbers are: ");
                    for (int l = 1; l <= 6; l++)
                    {
                        int correctNum = rnd.Next(1, 50);
                        correctList[l] = correctNum;
                        Console.Write(correctNum + ", ");
                    }
                    for (int m = 0; m <= 6; m++)
                    {
                        if (manualList[m] == correctList[m])
                        {
                            userCorrect++;
                        }
                    }
                    Console.WriteLine("You got " + userCorrect + " correct Numbers");
                    switch (userCorrect)
                    {
                        case 1:
                            Console.WriteLine("You won 3 Euros!");
                            cash += 3;
                            break;
                        case 2:
                            Console.WriteLine("Nice! You won 7 Euros!");
                            cash += 7;
                            break;
                        case 3:
                            Console.WriteLine("Wow! You won 12 Euros!");
                            cash += 12;
                            break;
                        case 4:
                            Console.WriteLine("Amazing! You won 50 Euros!");
                            cash += 50;
                            break;
                        case 5:
                            Console.WriteLine("Incredible! You won 4.200 Euros!");
                            cash += 4200;
                            break;
                        case 6:
                            Console.WriteLine("JACKPOT! You won 830.000 Euros!");
                            cash += 830000;
                            break;

                    }
                    break;
                default:
                    Console.WriteLine("Invalid answer - Only answer 1 or 2!");
                    goto WrongRandomOption;
            }
            Console.WriteLine("Press any key to go back to Play Menu.");
            Console.ReadKey();
            PlayMenu();

        }
        static void SuperBet()
        {
            Console.WriteLine("Your Super Number tickets:\n");
            for (int y = 1; y <= superNumTickets; y++)
            {
                Console.WriteLine("  Super Number ticket Nr. " + y);
            }
            Console.Write("\nEnter the ticket number to bet on it: ");
            int superTicketNum = Convert.ToInt32(Console.ReadLine());
        }
        // The Bank Menu
        static void Bank()
        {
            Console.Clear();
            Console.WriteLine("=== BANK MENU ===");
            Console.WriteLine(" 1. Check balance");
            Console.WriteLine(" 2. Deposit");
            Console.WriteLine(" 3. Withdraw");
            Console.WriteLine(" 4. Invest (Coming Soon)");
            Console.WriteLine(" 5. Back to Main Menu");
        WrongBankMenu:
            Console.Write("\nEnter your option by typing out the number: ");
            bankoption = Convert.ToInt32(Console.ReadLine());

            switch (bankoption)
            {
                case 1:
                    Console.WriteLine("\nYour current bank balance is: " + balance + " Euros.");
                    Console.WriteLine("Your current balance of cash is: " + cash + " Euros.");
                    Console.WriteLine("\nPress any key to go back to Bank Menu.");
                    Console.ReadKey();
                    Bank();
                    break;
                case 2:
                NotEnoughCash:
                    Console.Write("Deposit amount: ");
                    deposit = Convert.ToInt32(Console.ReadLine());
                    if (deposit <= cash)
                    {
                        balance += deposit;
                        cash -= deposit;
                        Console.WriteLine("Successfully deposited " + deposit + " Euros!");
                    }
                    else
                    {
                        Console.WriteLine("You dont have enough to deposit this amount.");
                        Console.WriteLine("Your current maximum deposit amount is: " + cash + " Euros.\n");
                        goto NotEnoughCash;
                    }
                    Console.WriteLine("Press any key to go back to Bank Menu.");
                    Console.ReadKey();
                    Bank();
                    break;
                case 3:
                NotEnoughBalance:
                    Console.Write("Withdraw amount: ");
                    withdrawal = Convert.ToInt32(Console.ReadLine());
                    if (withdrawal <= balance)
                    {
                        balance -= withdrawal;
                        cash += withdrawal;
                        Console.WriteLine("Successfully withdrawn " + withdrawal + " Euros.");
                    }
                    else
                    {
                        Console.WriteLine("Your balance is smaller than your withdraw amount!");
                        Console.WriteLine("Your current maximum withdraw amount is: " + balance + " Euros.\n");
                        goto NotEnoughBalance;
                    }
                    Console.WriteLine("Press any key to go back to Bank Menu.");
                    Console.ReadKey();
                    Bank();
                    break;
                case 4:
                    Console.WriteLine("This feature is coming soon!\n");
                    Console.WriteLine("Press any key to go back to Bank Menu.");
                    Console.ReadKey();
                    Bank();
                    break;
                case 5:
                    Main();
                    break;
                default:
                    Console.WriteLine("Invalid option - Enter your option again: ");
                    goto WrongBankMenu;
            }

        }
        // All Code for working:
        static void Work()
        {

        }

    }
}
C# 数组 Random NullReferenceException

评论

2赞 Johan Donne 3/2/2022
对于这两个代码片段,我们没有足够的信息来查找异常的原因(例如,实例化的“全局”数组可能被未初始化的本地版本隐藏......请发布重现错误的完整代码段。randomList
8赞 Tim Schmelter 3/2/2022
这不应该导致 NullRef,而是使用您提供的代码导致 IndexOfOfRangeException,如下所示: dotnetfiddle.net/m1BjJh 而不是您需要或更改为 .也许是.z <= 6z < 5new int[5]new int[7]rndnull
5赞 Jeroen Mostert 3/2/2022
你初始化正确了吗?不幸的是,调试器根据行号报告错误“相差一”的情况并不少见。rnd
0赞 cloudified 3/2/2022
@JeroenMostert我像下面这样初始化了rnd:Random rnd = new Random();
0赞 cloudified 3/2/2022
@Austin我很肯定,它给了我 我现在还通过将 for 循环中的变量降低到并上传整个代码来修复 IndexOutOfRange 问题,因为我无法用更简单的代码@Johan Donne 重现问题System.NullReferenceException<= 5

答: 暂无答案