cannot get to display - c#

i need help getting this code to display the arrays but the code structure has to stay the same. i have created two arrays and i need to display both from individual methods, and i also need to search and display the marks of the students entered
this is my first code that i have done and really need help, thanks
class Program
{
static void Main()
{
collectStudentDetails();
promptForStudentQuery();
printStudentsmarks();
Console.ReadLine();
}
public static void collectStudentDetails()
{
Console.WriteLine("Please Specifiy How Many Student Details You Wish To Enter");
Console.WriteLine("");
int n = SafeReadInteger(0);
int[] StudentMarks = new int[n];
string[] StudentNames = new string[n];
for (int i = 0; i < StudentNames.Length; i++)
{
Console.WriteLine("Enter Name for student {0}", i + 1);
StudentNames[i] = SafeReadString(null);
Console.WriteLine("Enter Mark for Student {0}: ", i + 1);
StudentMarks[i] = SafeReadInteger(0);
}
}
static void findStudentmark()
{
bool foundStudent = false;
Console.WriteLine("Please Enter The Students Name To Find Their Marks");
Console.WriteLine("Please Press Enter To Continue");
Console.ReadLine();
}
static void printStudentsmarks()
{
Console.WriteLine("\nStudent Mark List");
Console.WriteLine("Please Press Enter To Continue");
Console.ReadLine();
promptForStudentQuery();
}
static bool promptForStudentQuery()
{
bool promptAgain = true;
Console.WriteLine();
Console.WriteLine(" 1. find a student's mark ");
Console.WriteLine(" 2. print all student marks");
Console.WriteLine(" 3. exit ");
Console.WriteLine();
int choice = SafeReadInteger(0);
if (choice == 1)
{
findStudentmark();
}
else if (choice == 2)
{
printStudentsmarks();
}
else if (choice == 3)
{
Environment.Exit(0);
}
else if (choice == 0)
{
Console.WriteLine("you entered an invalid option try again");
}
return promptAgain;
}
public static int SafeReadInteger(int defaultVal)
{
try
{
return int.Parse(System.Console.ReadLine());
}
catch
{
return defaultVal;
}
}
public static string SafeReadString(string defaultVal)
{
string temp = "";
temp = Console.ReadLine();
while (temp == "")
{
Console.WriteLine("You have entered nothing. Please enter a correct value.");
temp = Console.ReadLine();
}
return temp;
}
static void DisplayArray(int[] inputarray)
{
foreach (int x in inputarray)
{
Console.Write(" {0} ", x);
}
Console.WriteLine("");
}
static void DisplayArray2(string[] inputarray)
{
foreach (string x in inputarray)
{
Console.Write(" {0} ", x);
}
Console.WriteLine("");
}
}

Below is probably a rough way of doing it. First define the StudentName and StudentMarks at class level.
class Program
{
static int[] StudentMarks;
static string[] StudentNames;
static void Main()
{
collectStudentDetails();
promptForStudentQuery();
printStudentsmarks();
Console.ReadLine();
}
You need to update method printStudentsmarks() and findStudentmark() as:
static void findStudentmark()
{
Console.WriteLine("Please Enter The Students Name To Find Their Marks");
Console.WriteLine("Please Press Enter To Continue");
string stdName = Console.ReadLine();
int i = 0;
for (i = 0; i < StudentNames.Length; i++)
{
if (string.Compare(stdName, StudentNames[i], true)==0)
{
break;
}
}
Console.WriteLine(StudentNames[i]);
Console.WriteLine(StudentMarks[i]);
}
static void printStudentsmarks()
{
Console.WriteLine("\nStudent Mark List");
for (int i = 0; i < StudentNames.Length; i++)
{
Console.Write("Name: ");
Console.WriteLine(StudentNames[i]);
Console.WriteLine("Marks: ");
Console.WriteLine(StudentMarks[i]);
Console.WriteLine("______________________________");
}
Console.WriteLine("Please Press Enter To Continue");
Console.ReadLine();
promptForStudentQuery();
}

Related

Hangman - when I enter a wrong letter, the message system index out of range appears

I am trying to make a hangman game in the console app but got a message index out of range.
The image below shows that I can enter a letter. If I enter a wrong letter I can enter a new letter after entering a new letter I get the message system out of range.
I think the error can be found within the method public bool raadletter (char letter).
This program contains 2 classes, the first class is the galgjespel class (hangmangame) and the second class is the program class.
//I got this stacktrace value
~
error message
at galgje2.GalgjeSpel.Raadletter(Char letter) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Galgjespel.cs: line 37
at galgje2.Program.Speelgalgje(GalgjeSpel galgje) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 128
at galgje2.Program.Start() in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 28
at galgje2.Program.Main(String[] args) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 14
~
//
class GalgjeSpel
{
public string secretWord;
public string guessedWord;
public void Init(string secretword)
{
this.secretWord = secretword;
this.guessedWord="";
char[] letter = new char [secretword.Length];
for (int i =0; i< letter.Length; i++)
{
this.guessedWord += ".";
}
}
public bool Raadletter(char letter)
{
char[] guesses = guessedWord.ToArray();
guessedWord = "";
if (secretWord.Contains(letter))
{
for(int i=0; i<secretWord.Length; i++)
{
// somewhere on this place i get the index out of range message
if (secretWord[i]==letter)
{
guesses[i] = letter;
}
}
foreach(var element in guesses)
{
guessedWord += element;
if (element!='.')
{
Console.Write($"{element} ");
}
else
{
Console.Write($". ");
}
}
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("------------------------------");
Console.ResetColor();
Console.WriteLine();
// return true;
}
else
{
Console.WriteLine("letter does not match secretword");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("------------------------------");
Console.ResetColor();
}
return false;
}
}
////
class Program
{
static void Main(string[] args)
{
Program myProgam = new Program();
myProgam.Start();
Console.ReadKey();
}
void Start()
{
GalgjeSpel galgje = new GalgjeSpel();
galgje.Init("eetlepel");
List<string> woordenlijst = WoordenLijst();
string nieuwwoord= SelecteerWoord(woordenlijst);
galgje.Init(nieuwwoord);
ToonWoord(nieuwwoord);Speelgalgje(galgje);
//Console.WriteLine("Het geheime woord is: " + galgje.geheimWoord);
//Console.WriteLine("Het geraden woord is: " + galgje.geradenWoord);
}
List <string> WoordenLijst()
{
List<string> Woordenlijst = new List<string>();
Woordenlijst.Add("slapen");
Woordenlijst.Add("poepen");
Woordenlijst.Add("eten");
Woordenlijst.Add("vakantie");
Woordenlijst.Add("reizen");
return Woordenlijst;
}
string SelecteerWoord(List<string> woorden)
{
GalgjeSpel gaglje = new GalgjeSpel();
Random rnd = new Random();
int randomwoord = rnd.Next(1, 5);
string nieuwwoord = woorden[randomwoord];
gaglje.secretWord = nieuwwoord;
return nieuwwoord;
}
void ToonWoord(string woord)
{
GalgjeSpel galgje = new GalgjeSpel();
Console.Write($"The secret word is : ");
char[] letter = woord.ToArray();
for (int i = 0; i< woord.Length; i++)
{
galgje.secretWord += letter[i];
Console.Write($"{letter[i]} ");
}
Console.WriteLine();
Console.Write("the guessed word is : ");
for (int i = 0; i < woord.Length; i++)
{
galgje.guessedWord += (". ");
Console.Write(". ");
}
Console.WriteLine();
}
void ToonLetter(List<char> letters)
{
Console.Write("the letters entered are : ");
foreach (var element in letters)
{
Console.Write($" {element} ");
}
Console.WriteLine();
}
char LeesLetter(List<char> geheimeletters)
{
char letter;
do
{ Console.WriteLine();
Console.Write("enter a letter : ");
letter = char.Parse(Console.ReadLine());
return letter;
} while (geheimeletters.Contains(letter));
{
}
}
bool Speelgalgje(GalgjeSpel galgje)
{
//char lijst van ingevoerde letters
List<char> ingevoerdeLetters = new List<char>();
// char lijst van geheime letters
List<char> geheimeletters = new List<char>();
// zet elke geheime letter in een char array
char[]geheimewoord = galgje.secretWord.ToArray();
// voeg elke char letter toe aan lijst van geheime letters
for (int i=0; i<geheimewoord.Length; i++)
{
geheimeletters.Add(geheimewoord[i]);
if (galgje.guessedWord == galgje.secretWord)
{
return true;
}
else
{ char letter = LeesLetter(geheimeletters);
ingevoerdeLetters.Add(letter);
ToonLetter(ingevoerdeLetters);
galgje.Raadletter(letter);
}
}return false;
}
}
The problem lies in the code before the point of the exception
public bool Raadletter(char letter)
{
char[] guesses = guessedWord.ToArray();
// Here guessedWord is truncated
guessedWord = "";
// Now if the letter is not in the secretword you don repopulate the guessedword
// So at the next loop the code builds a guesses array
// that doesn't match anymore to the secretWord length
if (secretWord.Contains(letter))
{
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == letter)
{
guesses[i] = letter;
}
}
// Here you rebuild the guessedWord, but only if you have a match
foreach (var element in guesses)
{
guessedWord += element;
....
}
}
else
{
// fail messages
}
The solution is to close the if and rebuild the guessedWord in each case
char[] guesses = guessedWord.ToArray();
guessedWord = "";
if (secretWord.Contains(letter))
{
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == letter)
{
guesses[i] = letter;
}
}
}
foreach(var element in guesses)
{
guessedWord += element;
.....
}

console c# - tik tak toe - saving the field?

I am just in my early days of learning C# and I got the task to build a "Tik Tak Toe" - game via console application; but I have a huge problem seeing mistakes in my code: when I enter a line and a column, the program will just print the pawn and color from the first player. And somehow my second problem is, that when it comes to the next player, the console won't save the current game stats and will draw a new field.
What did I code wrong?
namespace Tik_Tak_Toe_
{
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int column;
static int line;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning==true)
{
UPDATE();
}
Console.ReadLine();
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
Console.WriteLine("Player " + (i + 1) + ", enter your name!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", choose a color: ");
ColorConfiguration();
Console.WriteLine("... and your symbol example: X or O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blue":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "yellow":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "white":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "red":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "darkblue":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", it's your turn!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for ( column=0; column<field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column+1) + "|");
Console.ResetColor();
for ( line=0; line<field.GetLength(0); line++)
{
if (field[column,line]==0 && (column != playercolumn || line != playerline))
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[playercolumn, playerline]].color;
Console.Write(" " + p[field[playercolumn, playerline]].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("First, choose a column: ");
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (column < 1 || column > 3)
{
Console.WriteLine("Choose a column.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Choose a column.");
}
}
playercolumn -= 1;
Console.WriteLine("... and now a line");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (line < 1 || line > 3)
{
Console.WriteLine("Choose a line.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Choose a line.");
}
}
playerline -= 1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
}
You just have just global variables to store playercolumn and playerline.
Each time you execute PlayerInputyou will replace the values this variables had.
You will need a 3x3 matrix to store the player choices, then print this matrix as a board. Id a column and row was already chosen, you need to refuse the user input.
Looks like you want to store user moves in field global variable, but you're not assigning that anywhere.
I modified the code, in update, repeat the PlayerInput until a its valid for update:
do
{
PlayerInput();
} while (!UpdateField());
In DrawField check onli for values in field variable, not the player input
static void DrawField()
{
for (column = 0; column < field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column + 1) + "|");
Console.ResetColor();
for (line = 0; line < field.GetLength(0); line++)
{
if (field[column, line] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[column, line] - 1].color;
Console.Write(" " + p[field[column, line] - 1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
And implemented the UpdateField:
static bool UpdateField()
{
if (field[playercolumn, playerline] != 0)
{
Console.WriteLine("Column already chosen");
return false;
}
field[playercolumn, playerline] = currentplayer + 1;
return true;
}
It still need to check when the game finish.
You've got a lot of problems in your code. First of all, you was never storing the player input in the field array, so obviously when you were redrawing the table, only the last input was drawn. You were also exchanging some variables as line and playerline. After solving this problems and some minor ones and adding a Player class (i hope it is more or less like this as you don't provided it) , the code that correctly draws the board is more or less this:
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning == true)
{
UPDATE();
}
Console.ReadLine();
}
public class Player
{
public string name { get; set; }
public char pawn { get; set; }
public ConsoleColor color { get; set;}
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
p[i] = new Player();
Console.WriteLine("Spieler " + (i + 1) + ", gib deinen Namen ein!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", wähle deine Farbe: ");
ColorConfiguration();
Console.WriteLine("... und nun dein Symbol z.B. X oder O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blau":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "gelb":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "weiss":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "rot":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "dunkelblau":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", du bist dran!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for (int line = 0; line < field.GetLength(1); line++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((line + 1) + "|");
Console.ResetColor();
for (int column = 0; column < field.GetLength(0); column++)
{
if (field[line, column] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[line, column]-1].color;
Console.Write(" " + p[field[line, column] -1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("Wähle zuerst eine Spalte: ");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (playerline < 1 || playerline > 3)
{
Console.WriteLine("Wähle eine Spalte.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Spalte.");
}
}
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (playercolumn < 1 || playercolumn > 3)
{
Console.WriteLine("Wähle eine Zeile.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Zeile.");
}
}
playercolumn -= 1;
Console.WriteLine("... und nun eine Spalte");
//field[line-1, column] = new int();
playerline -= 1;
field[playerline, playercolumn] = currentplayer+1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
Study this code and compare it with yours to see what were your mistakes. Of course, you must still check if a position is alreay taken,when one player has won and when there are no moves left and the result of the game is a draw.

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.

Is there a way to enter number without showing them immediately?

I want to enter 10 numbers, and then show them in 1 line like this:
1,4,5,2,456,23,... and so on..
and it keeps writing them as I am entering them, and in the end when it's supposed to show all numbers in 1 line it shows only the last one.
I know it's possible with random numbers but when I enter them on my own I don't know how not to show them at all or keep them in 1 line and if it is even possible?
int a;
int x;
Console.WriteLine("a:");
a = int.Parse(Console.ReadLine());
x = 10;
for (int i = 0; i < x; i++)
{
a = int.Parse(Console.ReadLine());
}
Console.ReadKey();
you can use
Console.ReadKey(true)
it reads a key from console and does not show it.
you can use this to read word from console without showing it
public static string ReadHiddenFromConsole()
{
var word = new StringBuilder();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (word.Length > 0)
{
word.Remove(word.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
word.Append(i.KeyChar);
Console.Write("*");
}
}
return word.ToString();
}
You can use this code:
static void Main(string[] args)
{
int length = 10;
int[] myNumbers = new int[length];
for (int i = 0; i < length; i++)
{
Console.Write("Enter number:" );
myNumbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("Your numbers: {0}", string.Join(",", myNumbers));
}
i dont know how to write them at the end all in 1 line?
Well you need to save them as they are entered:
int num;
var nums = new List<int>();
while (nums.Count < 10)
{
Console.Write("Enter: ");
if (int.TryParse(Console.ReadLine(), out num))
{
nums.Add(num);
Console.Clear();
}
}
Console.WriteLine(string.Join(", ", nums));

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