Variable input on array is not read - c#

Guys I've been stuck for hours right now,
any help is appreciated.
I am currently building a console app to input a list on the number 1 option
and then present it on the number 2 option
My problem is the console doesn't seem to read my input specifically on this part here
Console.Write("Masukkan Judul".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Judul = Console.ReadLine();
I'm not sure what part should i post , so i copied all my code here
Thanks for your time
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp2
{
class Class1
{
enum Kategori
{
Textbook = 1, Kamus, Novel, Majalah
}
enum Penerbit
{
Gramedia = 1, Kompas, Tribun, Erlangga, Grasindo
}
struct Alas
{
public Kategori Kategori;
public Penerbit Penerbit;
public string Judul;
public double Harga;
public double Diskon;
public double Subtotal;
}
static void Main(string[] args)
{
Alas[] list = new Alas[0];
int pilih,jlhbuku,pil1,pil2 ;
double Total = 0;
Kategori Buku;
Penerbit Editor;
Ulang:
Console.Clear();
Console.Title= "Buku";
Console.WriteLine(new string(' ', 18)+"MENU");
Console.WriteLine(new string('=', 40));
Console.WriteLine("1. Input Data");
Console.WriteLine("2. Tampil Data");
Console.WriteLine("3. Keluar");
Console.WriteLine(new string('=', 40));
Console.Write("Masukkan Kode [1-3] : ");
pilih = int.Parse(Console.ReadLine());
if (pilih ==1)
{
Array.Resize(ref list, list.Count() + 1);
Console.Clear();
Console.WriteLine(new string('=', 40));
Console.WriteLine(new string(' ', 15) + "INPUT DATA");
Console.WriteLine(new string('=', 40));
Console.Write("Masukkan jumlah buku : ");
jlhbuku = int.Parse(Console.ReadLine());
Array.Resize(ref list, list.Count() + jlhbuku);
for (int i = 1; i <= list.GetUpperBound(0); i++)
{
Console.WriteLine("\nKategori Buku:");
Console.WriteLine("1. Textbook");
Console.WriteLine("2. Kamus");
Console.WriteLine("3. Novel");
Console.WriteLine("4. Majalah");
Console.Write("Masukkan Kategori [1-4] : ");
pil1 = int.Parse(Console.ReadLine());
Buku = (Kategori)pil1;
if (pil1 == 1)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Textbook;
}
if (pil1 == 2)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Kamus;
}
if (pil1 == 3)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Novel;
}
if (pil1 == 4)
{
list[list.GetUpperBound(0)].Kategori = Kategori.Majalah;
}
Console.WriteLine("\nPenerbit:");
Console.WriteLine("1. Gramedia");
Console.WriteLine("2. Kompas");
Console.WriteLine("3. Tribun");
Console.WriteLine("4. Erlangga");
Console.WriteLine("5. Grasindo");
Console.Write("Masukkan Penerbit [1-5] : ");
pil2 = int.Parse(Console.ReadLine());
Editor = (Penerbit)pil2;
if (pil1 == 1)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Gramedia;
}
if (pil1 == 2)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Kompas;
}
if (pil1 == 3)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Tribun;
}
if (pil1 == 4)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Erlangga;
}
if (pil1 == 5)
{
list[list.GetUpperBound(0)].Penerbit = Penerbit.Grasindo;
}
**Console.Write("Masukkan Judul".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Judul = Console.ReadLine();**
Console.Write("Masukkan Harga".PadRight(24) + ": ");
list[list.GetUpperBound(0)].Harga = double.Parse(Console.ReadLine());
Buku = (Kategori)list[list.GetUpperBound(0)].Kategori;
Editor = (Penerbit)list[list.GetUpperBound(0)].Penerbit;
list[list.GetUpperBound(0)].Diskon = 0.1* list[list.GetUpperBound(0)].Harga;
list[list.GetUpperBound(0)].Subtotal = list[list.GetUpperBound(0)].Harga - list[list.GetUpperBound(0)].Diskon;
}
goto Ulang;
}
if (pilih == 2)
{
if (list.Count() == 0)
{
Console.WriteLine("Belum ada pesanan.");
Console.ReadKey();
goto Ulang;
}
else
{
DateTime Date = DateTime.Now;
Console.Clear();
Console.Write("Tanggal : "+ (Date.ToString(" dd-MMMM-yyyy", new System.Globalization.CultureInfo("id-ID"))));
Console.WriteLine();
Console.WriteLine(new string('=', 80));
Console.WriteLine("Kategori".PadRight(10) +"Penerbit".PadRight(10) +"Judul".PadRight(15) + "Harga".PadRight(15) + "Diskon".PadRight(15) + "Subtotal");
Console.WriteLine(new string('=', 80));
for (int i = 0; i < list.GetUpperBound(0); i++)
{
Console.WriteLine(list[i].Kategori.ToString().PadRight(10) + list[i].Penerbit.ToString().PadRight(10) + list[i].Judul.ToString().PadRight(15) + list[i].Harga.ToString().PadRight(15) + list[i].Diskon.ToString("N2").PadRight(15) + list[i].Subtotal.ToString());
Total += list[i].Subtotal;
}
Console.WriteLine(new string('=', 80));
Console.Write(new string(' ', 57)+"Total : " + Total.ToString("Rp #.###,00"));
Console.ReadKey();
goto Ulang;
}
}
if (pilih == 3)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("Kode tidak valid.");
Console.ReadKey();
goto Ulang;
}
Console.ReadKey();
}
}
}

When you fill your data, you do this:
for (int i = 1; i <= list.GetUpperBound(0); i++)
But when you print your data, you do this:
for (int i = 0; i < list.GetUpperBound(0); i++)
Hence, you try to print list[0], which does not have any data. Therefore, you get a NullReferenceException when accessing the string variable.

Related

Sum of value in lists using c# -- BlackJack

I'm creating this Blackjack game and I'm having trouble calculating the total value of both the dealer and player. I've created a method to calculate the value for both the player(PlayerTotalCalculate) and the dealer (DealerTotalCalculate) using forloops.
When I run the program, the first sequence of cards are added up correctly, but when I "HIT" to get a new card for the player, it takes the previous value shown and adds the new card given as well as the value of the 2 cards given previously..
using System;
using System.Collections.Generic;
namespace BlackJack2
{
internal class Program
{
//GLOBAL VARIABLES
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
enum Phase { StartGame, DealersFirst, PlayersTurn, DealersTurn, ChooseWinner, End }
static Phase currentPhase;
static int userInput;
static void Main(string[] args)
{
string suitFace = "";
int dealersTotalValue = 0;
int playersTotalvalue = 0;
//Creating the list of cards
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
suitFace = "Diamonds";
break;
case 1:
suitFace = "Spades";
break;
case 2:
suitFace = "Hearts";
break;
case 3:
suitFace = "Clubs";
break;
}
myListOfCards.Add(new Card("King", suitFace, 10));
myListOfCards.Add(new Card("Queen", suitFace, 10));
myListOfCards.Add(new Card("Jack", suitFace, 10));
myListOfCards.Add(new Card("10", suitFace, 10));
myListOfCards.Add(new Card("9", suitFace, 9));
myListOfCards.Add(new Card("8", suitFace, 8));
myListOfCards.Add(new Card("7", suitFace, 7));
myListOfCards.Add(new Card("6", suitFace, 6));
myListOfCards.Add(new Card("5", suitFace, 5));
myListOfCards.Add(new Card("4", suitFace, 4));
myListOfCards.Add(new Card("3", suitFace, 3));
myListOfCards.Add(new Card("2", suitFace, 2));
myListOfCards.Add(new Card("Ace", suitFace, 1));
}
for (int i = 0; i < playersHand.Count; i++)
{
playersHand.Remove(playersHand[i]);
}
for (int i = 0; i < dealersHand.Count; i++)
{
dealersHand.Remove(dealersHand[i]);
}
//Assigning the first phase
currentPhase = Phase.DealersFirst;
DealersTurn(dealersTotalValue, playersTotalvalue);
}
//Deal Card Method using Random Number Generator
static void DealCard(int dealerTotalValue, int playersTotalValue)
{
Random r = new Random();
int randomNumber = r.Next(0, myListOfCards.Count);
if (currentPhase == Phase.DealersFirst || currentPhase == Phase.DealersTurn)
{
dealersHand.Add(myListOfCards[randomNumber]);
}
else if (currentPhase == Phase.PlayersTurn)
{
playersHand.Add(myListOfCards[randomNumber]);
//PlayerTotalCalulate(ref playersTotalValue);
}
myListOfCards.RemoveAt(randomNumber);
}
//Determining dealer's actions
static void DealersTurn(int dealersTotalvalue, int playersTotalValue)
{
if (currentPhase == Phase.DealersFirst)
{
for (int i = 0; i < 1; i++)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
}
DisplayDealerCards();
Console.WriteLine($"The dealer has a total value of: {dealersTotalvalue}");
currentPhase = Phase.PlayersTurn;
PlayersTurn(dealersTotalvalue, playersTotalValue);
}
else if (currentPhase == Phase.DealersTurn)
{
while (dealersTotalvalue < 15)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
DisplayDealerCards();
Console.WriteLine($"The dealer's new total is: {dealersTotalvalue}");
}
CalculateWinner(dealersTotalvalue, playersTotalValue);
}
}
static void PlayersTurn(int dealersTotalValue, int playersTotalValue)
{
for (int i = 0; i < 2; i++)
{
DealCard(dealersTotalValue, playersTotalValue);
}
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You have a total value of: {playersTotalValue}");
while (currentPhase == Phase.PlayersTurn)
{
Console.WriteLine("Would you like to hit or stay?");
Console.WriteLine("1: HIT or 2: STAY");
int.TryParse(Console.ReadLine(), out userInput);
if (userInput == 1)
{
DealCard(dealersTotalValue, playersTotalValue);
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You now have a total value of: {playersTotalValue}");
}
else if (userInput == 2)
{
currentPhase = Phase.DealersTurn;
DealersTurn(dealersTotalValue, playersTotalValue);
}
else
{
Console.WriteLine("Invalid input! Please try again.");
}
}
}
static void DisplayPlayerCards(int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
Console.WriteLine($"You were dealt a(n): {playersHand[i].DisplayCard()}");
}
PlayerTotalCalulate(ref playersTotalValue);
}
static void DisplayDealerCards()
{
//Showing only one card from the dealer
for (int i = 0; i < dealersHand.Count; i++)
{
Console.WriteLine($"The dealer is showing: {dealersHand[i].DisplayCard()}. The other card is hidden.");
}
}
static void CalculateWinner(int dealersTotalvalue, int playersTotalValue)
{
if (playersTotalValue > dealersTotalvalue && playersTotalValue < 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Great job! You've won!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue == dealersTotalvalue)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("The game is a tie!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue < dealersTotalvalue && playersTotalValue > 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Oh no! You've lost!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
//Console.WriteLine(PlayerTotalCalulate(ref playersTotalValue));
}
static void PlayerTotalCalulate(ref int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
playersTotalValue += playersHand[i].Value;
}
}
static void DealerTotalCalculate(ref int dealersTotalValue)
{
for (int i = 0; i < dealersHand.Count; i++)
{
dealersTotalValue += dealersHand[i].Value;
}
}
static void DisplayAllCards()
{
for (int i = 0; i < myListOfCards.Count; i++)
{
Console.WriteLine(myListOfCards[i].DisplayCard());
Console.WriteLine("\n\r\t");
}
}
static void DisplayingSingleCard()
{
Console.WriteLine(myListOfCards[0].DisplayCard());
}
}
}
I've also provided a screenshot of the console itself.
ConsolePicture
In DealerTotalCalculate, you should set dealersTotalValue to 0 before you add up the cards.
You need to do that in PlayerTotalCalulate as well.
As said in my comment, it's because your total variable is never reseted. So when you call the method to add the new value, it takes also the old value into consideration. So you just need to do total = 0, before calling the compute method.
Also consider this to simplify your compute method :
int[] array = { 1, 2, 3, 4, 5 };
int sum = array.Sum();
Console.WriteLine(sum);
It's slightly better, regarding code readability in my opinion. Not a big deal at all.

How to make a game move continuously

I'm trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). I've got halfway through, however, when a player makes a move, the board will simply reset to normal for the next move. Any thoughts on how I can make another move to the board and it takes into account the previous move?
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static string firstMove;
static bool gameStatus = true;
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
PlayingGame();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n"+ reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void InitialBoardSetUp()
{
Console.WriteLine(underline + "This is how the board is formatted:\n" + reset);
Thread.Sleep(750);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
Console.Write("███ ");
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 8);
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 8);
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, CompStackSelection);
Thread.Sleep(1000);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == CompStackSelection && i <= CompRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.WriteLine();
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == PlayerStackSelection && i <= PlayerRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayingGame()
{
int gameNumber = 1;
while (gameStatus == true)
{
Console.WriteLine(underline + "Round " + gameNumber+ ":\n" + reset);
WhoGoesFirst();
if (firstMove == "Computer")
{
ComputerMove();
}
else
{
PlayerMove();
}
gameNumber += 1;
playAgain();
}
}
static void playAgain()
{
Console.Write("Do you wish to play again? (Y/N): ");
char playAgain = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
if (playAgain == 'Y')
{
gameStatus = true;
}
else if (playAgain == 'N')
{
gameStatus = false;
}
}
In PlayingGame() you need to create a game loop.
static void PlayingGame()
{
int turn = // randomly choose 0 or 1 (whose turn is it)
bool finished = false;
while(!finished)
{
if(turn==0)
{
ComputerMove();
} else {
PlayerMove();
}
finished = CheckForEndOfGame();
turn = 1 - turn;
}
}
I do strongly suggest to create a Game class that handles the logic of the game and separate the UI (like messages etc) from the game mechanics. This is C# after all, and object oriented approaches are strongly encouraged.
You need to keep track of that game board and whose turn it is and what has been played in this Game class and display on the screen things based on the values (the state) of the game.

get access to variables inside switch case statement

I would like to ask how to get access to data collected inside case 1: statement and display information inside case 2: I don't have access to variables from case 1.
I wonder if it is possible to return the value of these variables and reuse them in the second case for display only.
As a part of project, I used some methods to deliver data to the main method.
using System;
namespace Employee_details
{
class Program
{
static void Main(string[] args)
{
//Employees detail info
int userInput = 0;
int numberEmployees = 0;
string[,] table;
string[,] newTable;
string name = "";
string surname = "";
string phone = "";
string email = "";
int row = 0;
while (userInput != 3)
{
Console.WriteLine("Menu");
Console.WriteLine("1 - Create the table");
Console.WriteLine("2 - Show content of the table");
Console.WriteLine("3 - Exit");
Console.WriteLine("Type the option number");
userInput = Convert.ToInt32(Console.ReadLine());
table = new string[numberEmployees, 4]; // [col, row]
newTable = tableRestaurant(table);
switch (userInput)
{
case 1:
Console.WriteLine("How many employees does your company have ?: ");
numberEmployees = Convert.ToInt32(Console.ReadLine());
table = new string[numberEmployees, 4]; // [col, row]
newTable = tableRestaurant(table);
for (row = 0; row < numberEmployees; row++)
{
//Name
Console.WriteLine("Write the name for user " + (row + 1));
name = Console.ReadLine();
string name3 = nameClient(name);
table[row, 0] = name3;
//Surname
Console.WriteLine("Write the surname for user " + (row + 1));
surname = Console.ReadLine();
string surname3 = surnameClient(surname);
table[row, 1] = surname;
// Phone Number
while (true)
{
Console.WriteLine("Write the phone for user " + (row + 1));
phone = Console.ReadLine();
string phone3 = phoneClient(phone);
if (phone3.Length == 11)
{
table[row, 2] = phone3;
break;
}
else
{
Console.WriteLine("Invalid phone number");
continue;
}
}
//Email
while (true)
{
Console.WriteLine("Write the email for user " + (row + 1));
email = Console.ReadLine();
string email3 = emailClient(email);
int charPos = email3.IndexOf('#');
if (charPos > 0)
{
table[row, 3] = email3;
break;
}
else
{
Console.WriteLine("Invalid email format");
continue;
}
}
}
Console.WriteLine();
Console.WriteLine("Thank you for providing all data. We will keep this data safe.");
Console.WriteLine();
Console.WriteLine();
break;
case 2:
table = new string[numberEmployees, 4]; // [col, row]
newTable = tableRestaurant(table);
int rowLength = newTable.GetLength(0);
int colLength = newTable.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", newTable[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("Type any key to continue....");
Console.ReadLine();
break;
default:
break;
}
}
}
public static string nameClient(string name)
{
return name;
}
public static string surnameClient(string surname)
{
return surname;
}
public static string emailClient(string email)
{
return email;
}
public static string phoneClient(string phone)
{
return phone;
}
public static string[,] tableRestaurant(string[,] table)
{
return table;
}
}
}

Error in parsing an input string to int value in c#

First if works great
Second if throws an exception
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray;
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0);
}
if (numbersArray[i] > numbersArray[i - 1])
{
if (numInput == "") {
break;
}
}
}
i++;
}
Console.WriteLine("You entered this series: ");
for (int j = 0; j < numbersArray.Length; j++)
{
Console.WriteLine(" " + numbersArray[j]);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
}
}
You can't parse a string wihout digits like numInput = ""
EDIT: Try this code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray = new []{1};
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
if (numInput == null || !numInput.All(char.IsDigit)) continue;
if (numInput != "")
{
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0); // <-- Code is unreachable!
}
}
i++;
}
else if(i >= 1)
{
break;
}
}
Console.WriteLine("You entered this series: ");
foreach (int t in numbersArray)
{
Console.WriteLine(" " + t);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
Console.ReadLine();
}
I assume you are trying to look at a index not existing.
Not sure of your language but I guess numbersArray[0] is the first index and numbersArray[1] is the second. So when you input your first number then you try to look at numbersArray[1] which doesn't exist.

Keeping track of what the user inputs

This is my hangman code, and its almost good up to the point where it displays the guessed letters. It only displays the most recent guessed letter but I want it to continue on from whats left off. Such as if a person guess "A" and then "L" then Guessed letters are A, L.
I tried using a for loop after "Guessed letters are" but then it gives me the output
"A, A, A, A, A". What should I do to fix this problem?
class Hangman
{
public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
public string[] torture = new string[6] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
public char[] guessed = new char[26];
int i;
public void randomizedWord()
{
Random random = new Random();
int index = random.Next(0, 5);
char[] hidden = new char[words[index].Length];
string word = words[index];
Console.WriteLine(words[index]);
Console.Write("The word is: ");
for (i = 0; i < hidden.Length; i++)
{
Console.Write('-');
hidden[i] = '-';
}
Console.WriteLine();
int lives = 6;
do
{
Console.WriteLine("Guess a letter: ");
char userinput = Console.ReadLine().ToCharArray()[0];
index++;
guessed[index] = userinput;
Console.WriteLine("Guessed letters are: " + guessed[index]);
bool foundLetter = false;
for (int i = 0; i < hidden.Length; i++)
{
if (word[i] == userinput)
{
hidden[i] = userinput;
foundLetter = true;
Console.WriteLine("You guessed right!");
}
}
for (int x = 0; x < hidden.Length; x++)
{
Console.Write(hidden[x]);
}
if (!foundLetter)
{
Console.WriteLine(" That is not a correct letter");
lives--;
if (lives == 5)
{
Console.WriteLine("You lost a " + torture[0]);
}
else if (lives == 4)
{
Console.WriteLine("You lost the " + torture[1]);
}
else if (lives == 3)
{
Console.WriteLine("You lost your " + torture[2]);
}
else if (lives == 2)
{
Console.WriteLine("You lost the " + torture[3]);
}
else if (lives == 1)
{
Console.WriteLine("You lost your " + torture[4]);
}
else
{
Console.WriteLine("You lost your " + torture[5]);
Console.WriteLine("You lose!");
break;
}
}
bool founddash = false;
for (int y = 0; y < hidden.Length; y++)
{
if (hidden[y] == '-')
{
founddash = true;
}
}
if (!founddash)
{
Console.WriteLine(" You Win! ");
break;
}
Console.WriteLine();
} while (lives != 0);
}
I was going to post on your other thread Hangman Array C#
Try changing this line
Console.WriteLine("Guessed letters are: " + guessed[index]);
To
Console.WriteLine("Guessed letters are: " + string.Join(" ", guessed).Trim());
I had a play with your hangman game and came up with this solution (while we are doing your homework). Although not related to the question.
public class HangCSharp
{
string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
List<char> guesses;
Random random = new Random();
string word = "";
string current = "";
int loss = 0;
readonly int maxGuess = 6;
int highScrore = 0;
public void Run()
{
word = words[random.Next(0, words.Length)];
current = new string('-', word.Length);
loss = 0;
guesses = new List<char>();
while (loss < maxGuess)
{
Console.Clear();
writeHeader();
writeLoss();
writeCurrent();
var guess = Console.ReadKey().KeyChar.ToString().ToUpper()[0];
while (!char.IsLetterOrDigit(guess))
{
Console.WriteLine("\nInvalid Guess.. Please enter a valid alpha numeric character.");
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
while (guesses.Contains(guess))
{
Console.WriteLine("\nYou have already guessed {0}. Please try again.", guess);
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
guesses.Add(guess);
if (!isGuessCorrect(guess))
loss++;
else if (word == current)
break;
}
Console.Clear();
writeHeader();
writeLoss();
if (loss >= maxGuess)
writeYouLoose();
else
doYouWin();
Console.Write("Play again [Y\\N]?");
while (true)
{
var cmd = (Console.ReadLine() ?? "").ToUpper()[0];
if (cmd != 'Y' && cmd != 'N')
{
Console.WriteLine("Invalid Command. Type Y to start again or N to exit.");
continue;
}
else if (cmd == 'Y')
Run();
break;
}
}
bool isGuessCorrect(char guess)
{
bool isGood = word.IndexOf(guess) > -1;
List<char> newWord = new List<char>();
for (int i = 0; i < word.Length; i++)
{
if (guess == word[i])
newWord.Add(guess);
else
newWord.Add(current[i]);
}
current = string.Join("", newWord);
return isGood;
}
void writeCurrent()
{
Console.WriteLine("Enter a key below to guess the word.\nHint: {0}", current);
if (guesses.Count > 0)
Console.Write("Already guessed: {0}\n", string.Join(", ", this.guesses));
Console.Write(":");
}
void writeHeader()
{
Console.WriteLine("Hang-CSharp... v1.0\n\n");
if (highScrore > 0)
Console.WriteLine("High Score:{0}\n\n", highScrore);
}
void writeYouLoose()
{
Console.WriteLine("\nSorry you have lost... The word was {0}.", word);
}
void doYouWin()
{
Console.WriteLine("Congratulations you guessed the word {0}.", word);
int score = maxGuess - loss;
if (score > highScrore)
{
highScrore = score;
Console.WriteLine("You beat your high score.. New High Score:{0}", score);
}
else
Console.WriteLine("Your score:{0}\nHigh Score:{1}", score, highScrore);
}
void writeLoss()
{
switch (loss)
{
case 1:
Console.WriteLine(" C");
break;
case 2:
Console.WriteLine(" C{0} #", Environment.NewLine);
break;
case 3:
Console.WriteLine(" C\n/#");
break;
case 4:
Console.WriteLine(" C\n/#\\");
break;
case 5:
Console.WriteLine(" C\n/#\\\n/");
break;
case 6:
Console.WriteLine(" C\n/#\\\n/ \\");
break;
}
Console.WriteLine("\n\nLives Remaining {0}.\n", maxGuess - loss);
}
}
Can be run as new HangCSharp().Run();
The index variable is being set to a random number when the random word is selected in this line.
int index = random.Next(0, 5);
Then that index is being used to store the guesses in the do..while loop. However, since index starts from a random number between 0 and 5 you see unexpected behaviour.
Set index to 0 in the line before the do..while loop and the for loop (or the alternatives suggested elsewhere) should work e.g. as so
index = 0;
int lives = 6;
do
{
// rest of the code

Categories