I'm just starting c# and I'm following Bob Tabor's C# Fundamentals for Absolute Beginners and part of the course information it gives a companion guide. On the Module 6 lab I'm stuck on trying to figure out how to draw a card in a game of black jack. I'm trying to stick to the course material so I would like to try to figure this out using arrays vs list which I know would be easier.
So my problem is that I'm not sure at the end why my return drawCard[0]
throws an exception
Index was outside the bounds of the array
when I am specifically calling position 0 and how would I go about fixing this?
public Card DrawCard()
{
// Will generate a random number between 0 and 51.
Random getRandomNumber = new Random();
int randomNumber = getRandomNumber.Next(0, 52);
// Created array drawnCard so I could set array Cards = to it.
Card[] drawnCard = new Card[0];
// Checks to see if the deck is empty.
if (cardsDrawn == 52)
{
drawnCard[0] = null;
Console.WriteLine("No cards left to draw.");
}
// Sets the drawnCard to a random card pulled from the deck.
else if (Cards[randomNumber] != null)
{
Array.Copy(Cards, randomNumber, drawnCard, 0, 0);
//drawnCard[0] = Cards[randomNumber];
Cards[randomNumber] = null;
cardsDrawn++;
}
else
{
// Keeps looping until cards has been drawn.
while (Cards[randomNumber] == null)
{
randomNumber = RandomGenerator.Next(0, 52);
if (Cards[randomNumber] != null)
{
Array.Copy(Cards, randomNumber, drawnCard, 0, 0);
//drawnCard[0] = Cards[randomNumber];
Cards[randomNumber] = null;
cardsDrawn++;
}
}
}
return drawnCard[0];
}
Aucun commentaire:
Enregistrer un commentaire