Hangman Console Application - c#

I am currently working on a small project where I am creating a hangman game as a console application. Currently, I am having problems because I want to create an array for the word that is to be guessed. This word is not random and will always be the same. In this case, it is "miller". I want to create an array for "miller" and have a loop to display each letter in the word character array. When the letter is guessed correctly, I want to display the correct letter and if not display the special character "*" in its stead. So, for instance, the word is "miller" and would be first displayed as "******". When the user guessed a letter correctly, one special character would become the correctly guessed letter. So, say the user guesses "i"...the displayed word would then be "*i****". Say he guesses "l" next...the displayed word would then be "*ill**". How would I go about doing this? This is my code so far... I've created already attempted to create an array for this. Sorry if this seems trivial, but I am new to programming and just need some guidance and help.
TLDR;
I need help with this code. I am trying to make an array containing 'miller' and I want to be able to call on that array when the user guesses a letter correct changing the display of a special character "*" to whatever the letter he guesses correctly is. I am told going about a for loop is the best route for this, but I'm kind of lost. Help?
static void Main(string[] args)
{
char[] guessed = new char[26];
char[] word = "miller".ToCharArray();
char guess;
int score = 0, index = 0;
Console.WriteLine("******");
for (int i = 0; i < 10; i++)
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
if (guess == l1 || guess == l2 || guess == l3 || guess == l4 || guess == l5 || guess == l6)
{
Console.WriteLine("Your guess is correct.");
guessed[index] = guess;
index++;
}
else
{
Console.WriteLine("Your guess is incorrect.");
score++;
}
}
Console.WriteLine("Your score is " + score);
Console.ReadLine();
}
}
}

I don't know if this is what you were looking for, maybe you should be more specific next time... but I tried to create a solution for your problem.
static void Main(string[] args)
{
char[] guessed = new char[26];
char[] testword = "******".ToCharArray();
char[] word = "miller".ToCharArray();
char[] copy = word;
char guess;
int score = 0, index = 0;
Console.WriteLine(testword);
for (int i = 0; i < 10; i++)
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
score++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine("Your score is " + score);
Console.ReadLine();
}

Include using System.Linq; in your file and here is your for loop.
for (int 1 = 0; i < 10; i++)
{
Console.Write("Please enter a letter to guess: ");
char guess = char.Parse(Console.ReadLine());
if(word.Contains(guess))//checks if the word is is the array word
{
//the guess was correct.
Console.WriteLine("Your guess is correct.");
guessed[index] = guess;
index++;
}
else
{
//the guess was wrong.
console.WriteLine("Your guess is incorrect.");
....
}
}
Hope this helps.

It looks like you're fairly close to there. The two things I'm uncertain about is the if statement "guess == l1 || guess == l2" etc etc...This can be handled with:
if(word.Contains(guess))
Second, you will need another for loop to go through the correctly guessed letters and place them.
for loop to fill in letters instead of asterisks:
put it at the beginning of for (int i = 10...)
for (int j = 0; j < word.Length; j++)
{
if (guessed.Contains(word[j]))
{
Console.Write(word[j]);
}
else
{
Console.Write("*");
}
}

Related

Try/catch in for-loop

I'm new to programming and trying to solve a problem. I've got an array I want to fill with input from a user but I want to make sure it's only integers between 1-25 and no string input. How do I do this?
The code I've gotten this far is this:
for (int i = 0; i < lottery.Length; i++)
{
Console.Write(i + ": ");
try
{
input = int.Parse(Console.ReadLine());
lottery[i] = input;
}
catch
{
Console.WriteLine("Only integers!");
i--;
}
}
This codes makes sure the only input to the array is integers but how do I get the user to only write numbers between 1-25? I've tried diffrent if-statements and other loops 3 hours but can't solve it. Please help.
You should not use exceptions to drive through your code. Exceptions are costly things in terms of performances and if there is a way to avoid them you should always use that way.
In your case you should use int32.TryParse instead of Parse. This TryParse doesn't raise an exception if the input is not a valid integer number but returns false or true while the parsed number (if it is an integer) is returned in the out parameter passed to the method.
This allows to write a lot simpler code with a while loop to continue input in case of errors.
for (int i = 0; i < lottery.Length; i++)
{
Console.Write(i + ": ");
// Start the loop with an invalid input
int input = 0;
while(input == 0)
{
if(int32.TryParse(Console.ReadLine(), out input);
{
// Got a valid integer, add out acceptance logic here
if(input > 0 && input <= 25)
lottery[i] = input;
else
{
Console.WriteLine("Type a number between 1 and 25");
// Not a valid range. Force the loop to continue
input = 0;
}
}
else
Console.WriteLine("Write only integers between 1-25");
}
}
int[] lottery = new int[5];
for (int i = 0; i < lottery.Length; i++)
{
Console.WriteLine(i + ": ");
int input;
while(true)
{
string inp = Console.ReadLine();
if(Int32.TryParse(inp, out input) == true)
{
if (0 < input & input <= 25)
{
break;
}
else
{
Console.WriteLine("Only numbers 1-25");
}
}
else
{
Console.WriteLine("Only Integers");
}
}
lottery[i] = input;
}

C# Array - identify the input if it is repeating or not

I want to create an algorithm that would identify if the user input is repeating or not. If it is repeating it will prompt the user a message if its not repeating it will continue the process.
public static class Program
{
public static void Main()
{
Console.WriteLine("input array of numbers: );
int[] array = new int[4];
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(array[i] == array[0])
{
Console.WriteLine("repeating inputs")
}
}
Console.WriteLine("Highest number is:" + array.MaxLenght);
Console.ReadLine();
}
}
Explanation: The user will be prompted by message "inter array of numbers:" then the user will now input the numbers. If the user inputs the same number or if the number was already inputted, the user will be prompted by a message something like "repeating inputs! Input another number". After the user input another number unique to the previously interred the program will continue and print out the largest number base on the inputs.
i'm not sure if I understood you correctly but this is what i can extrapolated from your post :
you want to get input from the user and check if it's repeating or not and then print the highest number (based on your Console.WriteLine("Highest number is:" + array.MaxLenght); )
this is how i'd approach it
Console.WriteLine("input array of numbers: ");
List<int> uniqueInts = new List<int>();
int[] array = new int[4];
for (int i = 0; i < 3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if (!uniqueInts.Contains(array[i]))
uniqueInts.Add(array[i]);
}
//getting the max number
//assuming the first number is the max
int max = uniqueInts[0];
for (int i = 1; i < uniqueInts.Count; i++)
{
if (max < uniqueInts[i])
max = uniqueInts[i];
}
Console.WriteLine("The highest number is : " + max);
There are a lot of assumptions that I'm making with this answer. I'm assuming you're struggling to get the value of the item prior to the current iteration considering you have if(array[i] == array[0]).
If that's the case, then simply change array[0] to array[i-1].
Wait! Before you do that, you need to add a check to make sure you aren't on the first iteration. If you don't, you'll get an exception thrown on the first iteration, because you'll be trying to grab array[-1], which isn't valid.
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(i > 0)
{
if (array[i] == array[i-1])
Console.WriteLine("repeating inputs")
}
}
Make these few changes, and I think you'll get what you're after.

C# cant understand count

I am trying to count words in this program but i don't understand why the program is counting for 1 number less than it must be.
For example:
sun is hot
program will show me that there is only 2 words.
Console.WriteLine("enter your text here");
string text = Convert.ToString(Console.ReadLine());
int count = 0;
text = text.Trim();
for (int i = 0; i < text.Length - 1; i++)
{
if (text[i] == 32)
{
if (text[i + 1] != 32)
{
count++;
}
}
}
Console.WriteLine(count);
Regular expression works the best for this.
var str = "this,is:my test string!with(difffent?.seperators";
int count = Regex.Matches(str, #"[\w]+").Count;
the result is 8.
Counts all words, does not include spaces or any special characters, regardless if they repeat or not.

I want to search integers from string and store them in array

I'm building a console based lottery game where user enters his/her choice of numbers. I need to check that the numbers are between 1-39 and user has entered exactly 7 valid numbers. I'd like to do this in a way where user writes them in one line of string in console and the program finds any white space, comma or other non-digit characters and ignores them. The remaining lottery numbers should be stored in integer array which doesn't include any duplicates.
My current version is quite horrible since it gets errors very easily if user writes e.g. 2 spaces between numbers.
Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
string userRow = Console.ReadLine();
int[] userLottery = new int[7];
for(int i = 0; i < userLottery.Length; i++)
{
userLottery = userRow.Split(',', '.', ' ').Select(x => int.Parse(x)).ToArray();
if(userLottery[i] > 7)
{
Array.Resize(ref userLottery, 7);
}
}
I'd like to replace my current way in more convenient way where amount of user errors won't affect the program. If the user writes more than one space the error occures.
I have tried to build regular expression to handle these situations but I can't use it to store them in to array.
string userChoice = Console.ReadLine();
MatchCollection userNumbers = Regex.Matches(userChoice, #"\d+");
int[] userRow;
for(int i = 0; i < userNumbers.Count; i++)
{
userRow[i] = userNumbers[i].Value;
}
That says string can't be converted to int[]...
You could use this LINQ query using String.Split with RemoveEmptyEntries and int.tryParse:
int num = 0;
int[] userLottery = userRow.Trim()
.Split(new[] { '.', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(s => int.TryParse(s.Trim(), out num) && num > 0 && num < 40)
.Select(s => num)
.Distinct()
.ToArray();
if(userLottery.Length != 7)
Console.WriteLine("Enter 7 valid numbers between 1 and 39");
else
Console.WriteLine("You have chosen following numbers: " + string.Join(",", userLottery));
Enumerable.Distinct removes duplicates as requested.
Your code doesn't match the instruction to the user. The following does what you tell the user:
Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
int[] userLottery = new int[7];
int i = 0;
while (i < 7)
{
Console.Write("Your choice #{0}: ", i+1);
string userRow = Console.ReadLine();
int userNumber;
if (!Int32.TryParse(userRow, out userNumber) || userNumber < 1 || userNumber > 39)
{
Console.WriteLine("Invalid number! Please try again!");
}
else
{
userLottery[i++] = userNumber;
}
}
Use Regex.Split() for this to handle multiple white spaces.
string[] numbers = Regex.Split(userRow, #"\s+");
\s+ means one or more white spaces. You can use [ ]+ only for space if you want.
You can just parse it with RegEx first and then it should work.
using System.Text.RegularExpressions;
Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
string userRow = Console.ReadLine();
int[] userLottery = new int[7];
string[] userEnter = Regex.Split(userRow, " ");
int n = 0;
int k = 0;
for (int i = 0; i < userEnter.Length; i++)
{
bool isNumeric = int.TryParse(userEnter[i], out n);
if(isNumeric == true)
{
userLottery[k] = int.Parse(userEnter[i]);
k++;
}
}
Use the following code
Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
string data = Console.ReadLine();
int[] userLottery = new int[7];
int i = 0;
StringBuilder num = new StringBuilder();
foreach (char item in data)
{
if (!Char.IsDigit(item))
{
if (num.Length == 0)
continue;
userLottery[i] = int.Parse(num.ToString());
i++;
num.Clear();
continue;
}
num.Append(item);
}
if(num.Length > 0)
userLottery[i] = int.Parse(num.ToString());

Code showing wrong output

I have developed a program in c# which is doing "Insertion Sort", the code takes in a max value for the elements and the values of the elements and then one by one shows the steps of sorted values.
Code:
static void insertionSort(int[] ar)
{
for (int i = 1; i < ar.Length; i++)
{
int temp = ar[i];
int j = i - 1;
while (j >= 0 && ar[j] > temp)
{
ar[j + 1] = ar[j];
foreach (int val in ar)
Console.Write(val + " ");
Console.WriteLine();
j--;
}
}
}
static void Main(String[] args)
{
int ar_size;
ar_size = Convert.ToInt32(Console.ReadLine());
int[] ar = new int[ar_size];
for (int i = 0; i < ar_size; i++)
{
ar[i] = Convert.ToInt32(Console.Read());
}
insertionSort(ar);
Console.ReadKey();
}
The Sample Input That I Give:
5
2 4 6 8 3
The Output That Comes:
Can anyone explain me why is this happening!
Any help would be greatly appreciated! :)
Apart from the problems with your sort itself, the reason for the strange numbers in your result is that you use Console.Read very wrong. It returns the ASCII value of the character entered by the user. Furthermore, it will return the ASCII values for all entered characters, not only for the numbers.
So, the first call to Console.Read() will return 50 (ASCII value of '2').
The second call will return 32 (ASCII value of a space).
The third call will return 52 (ASCII value of '4').
etc.
To fix this, initialize ar like this:
var numbers = Console.ReadLine().Split(' ');
for (int i = 0; i < ar_size; i++)
ar[i] = Convert.ToInt32(numbers[i]);
Please note that this code lacks error handling. It will throw an exception in the followin circumstances:
The user entered anything besides spaces and numbers
The user entered less numbers than he specified in the first line

Categories

Resources